<?php
function content_center_root(){
    return __DIR__ . '/../data/content_center';
}

function content_center_safe_key($value){
    $value = strtolower(trim((string)$value));
    $value = preg_replace('/[^a-z0-9\.\-_]/', '-', $value);
    return trim($value, '-');
}

function content_center_now(){ return time(); }

function content_center_channels(){
    return array('news'=>'新闻资讯','product'=>'产品服务','case'=>'客户案例','faq'=>'常见问题');
}

function content_center_scopes(){
    return array('site'=>'当前站','theme'=>'当前主题','global'=>'全部主题');
}

function content_center_statuses(){
    return array('draft'=>'草稿','pending'=>'待发布','published'=>'已发布');
}

function content_center_article_id($article){
    if(!empty($article['id'])) return (int)$article['id'];
    if(!empty($article['article_id'])) return abs(crc32($article['article_id']));
    return abs(crc32(($article['title'] ?? '') . '|' . ($article['created_at'] ?? '')));
}

function content_center_title_part($title){
    $title = trim((string)$title);
    if($title === '') return 'untitled';
    $title = strip_tags($title);
    $title = preg_replace('~[\\\/:*?"<>|\r\n\t]+~u', '-', $title);
    $title = preg_replace('/\s+/u', '-', $title);
    $title = trim($title, " .-_\t\n\r\0\x0B");
    if(function_exists('mb_substr')) $title = mb_substr($title, 0, 48, 'UTF-8');
    else $title = substr($title, 0, 96);
    return $title !== '' ? $title : 'untitled';
}

function content_center_filename($article){
    $id = trim((string)($article['article_id'] ?? ''));
    if($id === '') $id = 'CNT' . date('YmdHis') . mt_rand(100,999);
    return $id . '-' . content_center_title_part($article['title'] ?? '') . '.php';
}

function content_center_build_dir($scope, $target, $channel='news'){
    $scope = in_array($scope, array('site','theme','global'), true) ? $scope : 'site';
    $channel = content_center_safe_key($channel ?: 'news');
    $target = content_center_safe_key($target);
    if($scope === 'global') return content_center_root() . '/global/' . $channel;
    if($scope === 'theme') return content_center_root() . '/themes/' . $target . '/' . $channel;
    return content_center_root() . '/sites/' . $target . '/' . $channel;
}

function content_center_infer_meta_from_file($file){
    $path = str_replace('\\', '/', $file);
    $root = str_replace('\\', '/', content_center_root());
    $rel = ltrim(str_replace($root, '', $path), '/');
    $parts = explode('/', $rel);
    $scope = 'site'; $target = ''; $channel = 'news';
    if(($parts[0] ?? '') === 'global'){
        $scope = 'global'; $target = 'all'; $channel = $parts[1] ?? 'news';
    }elseif(($parts[0] ?? '') === 'themes'){
        $scope = 'theme'; $target = $parts[1] ?? ''; $channel = $parts[2] ?? 'news';
    }elseif(($parts[0] ?? '') === 'sites'){
        $scope = 'site'; $target = $parts[1] ?? ''; $channel = $parts[2] ?? 'news';
    }
    return array($scope, $target, $channel, basename($file), $rel);
}

function content_center_read_raw($file){
    if(!is_file($file)) return null;
    $article = include $file;
    if(!is_array($article)) return null;
    list($scope, $target, $channel, $filename, $rel) = content_center_infer_meta_from_file($file);
    $article['scope'] = $article['scope'] ?? $scope;
    $article['target'] = $article['target'] ?? $target;
    $article['channel'] = $article['channel'] ?? $channel;
    $article['filename'] = $filename;
    $article['source_file'] = $filename;
    $article['source_path'] = $file;
    $article['relative_path'] = $rel;
    return $article;
}

function content_center_normalize($article, $source=''){
    if(!is_array($article)) return null;
    $status = $article['status'] ?? 'published';
    $publishTime = trim((string)($article['publish_time'] ?? ''));
    if($status !== 'published') return null;
    if($publishTime !== '' && strtotime($publishTime) > content_center_now()) return null;
    $article['id'] = content_center_article_id($article);
    $article['date'] = $article['date'] ?? ($publishTime ? date('Y-m-d', strtotime($publishTime)) : date('Y-m-d', intval($article['created_at'] ?? time())));
    $article['summary'] = $article['summary'] ?? ($article['description'] ?? excerpt($article['content'] ?? '', 90));
    if(($article['channel'] ?? '') === 'faq'){
        $article['question'] = $article['question'] ?? ($article['title'] ?? '');
        $article['answer'] = $article['answer'] ?? ($article['content'] ?? '');
    }
    $article['type'] = $article['type'] ?? (($article['channel'] ?? '') === 'product' ? '产品服务' : (($article['channel'] ?? '') === 'case' ? '客户案例' : (($article['channel'] ?? '') === 'faq' ? '常见问题' : '企业新闻')));
    $article['tags'] = $article['tags'] ?? array();
    $article['source_file'] = basename($source);
    return $article;
}

function content_center_read_dir($dir){
    $items = array();
    if(!is_dir($dir)) return $items;
    foreach(glob(rtrim($dir, '/') . '/*.php') as $file){
        $article = content_center_read_raw($file);
        $article = content_center_normalize($article, $file);
        if($article && !empty($article['title'])) $items[] = $article;
    }
    return $items;
}

function content_center_article_public_domain($article){
    $scope = $article['scope'] ?? 'site';
    $target = trim((string)($article['target'] ?? ''));
    if($scope === 'site' && $target !== '') return $target;
    $host = strtolower($_SERVER['HTTP_HOST'] ?? '');
    $host = explode(':', $host)[0];
    return $host;
}

function content_center_article_public_url($article){
    $domain = content_center_article_public_domain($article);
    if($domain === '') return array('', '');
    $channel = content_center_safe_key($article['channel'] ?? 'news');
    $id = content_center_article_id($article);
    return array($domain, '/' . $channel . '/' . intval($id) . '.html');
}

function content_center_push_realtime($article){
    if(($article['status'] ?? '') !== 'published') return;
    $publishTime = trim((string)($article['publish_time'] ?? ''));
    if($publishTime !== '' && strtotime($publishTime) > content_center_now()) return;
    $pushFile = __DIR__ . '/push_center.php';
    if(!function_exists('push_center_realtime') && is_file($pushFile)) include_once $pushFile;
    if(!function_exists('push_center_realtime')) return;
    list($domain, $path) = content_center_article_public_url($article);
    if($domain === '' || $path === '') return;
    push_center_realtime($domain, $path);
}

function content_center_publish_due_articles(){
    static $running = false;
    if($running) return 0;
    $running = true;
    $count = 0;
    foreach(content_center_all_files() as $file){
        $article = content_center_read_raw($file);
        if(!$article || ($article['status'] ?? '') !== 'pending') continue;
        $publishTime = trim((string)($article['publish_time'] ?? ''));
        if($publishTime === '' || strtotime($publishTime) > content_center_now()) continue;
        $article['status'] = 'published';
        $article['updated_at'] = date('Y-m-d H:i:s');
        $article['delay_publish'] = false;
        unset($article['filename'], $article['source_file'], $article['source_path'], $article['relative_path']);
        if(file_put_contents($file, "<?php\nreturn " . var_export($article, true) . ";\n", LOCK_EX) !== false){
            $count++;
            content_center_push_realtime($article);
        }
    }
    if($count > 0 && function_exists('static_cache_clear')) static_cache_clear();
    $running = false;
    return $count;
}

function content_center_load_articles($theme, $host='', $channel='news'){
    content_center_publish_due_articles();
    $root = content_center_root();
    $theme = content_center_safe_key($theme ?: 'industrial');
    $host = content_center_safe_key($host ?: ($_SERVER['HTTP_HOST'] ?? ''));
    $sets = array();
    $sets[] = content_center_read_dir($root . '/global/' . $channel);
    $sets[] = content_center_read_dir($root . '/themes/' . $theme . '/' . $channel);
    if($host !== '') $sets[] = content_center_read_dir($root . '/sites/' . $host . '/' . $channel);
    $items = array();
    foreach($sets as $set){ foreach($set as $item){ $items[] = $item; } }
    if(function_exists('article_sort_desc')){
        article_sort_desc($items);
    }else{
        usort($items, function($a,$b){ return strcmp($b['date'] ?? '', $a['date'] ?? ''); });
    }
    return $items;
}

function content_center_all_files(){
    $root = content_center_root();
    $files = array();
    if(!is_dir($root)) return $files;
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
    foreach($it as $file){
        $path = str_replace('\\', '/', $file->getPathname());
        if(strpos($path, '/.trash/') !== false) continue;
        if($file->isFile() && strtolower($file->getExtension()) === 'php') $files[] = $file->getPathname();
    }
    sort($files);
    return $files;
}

function content_center_trash_root(){
    return content_center_root() . '/.trash';
}

function content_center_trash_files(){
    $root = content_center_trash_root();
    $files = array();
    if(!is_dir($root)) return $files;
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
    foreach($it as $file){
        if($file->isFile() && strtolower($file->getExtension()) === 'php') $files[] = $file->getPathname();
    }
    sort($files);
    return $files;
}

function content_center_find_file($articleId){
    $articleId = trim((string)$articleId);
    if($articleId === '') return '';
    foreach(content_center_all_files() as $file){
        $article = content_center_read_raw($file);
        if(!$article) continue;
        if(trim((string)($article['article_id'] ?? '')) === $articleId) return $file;
    }
    return '';
}

function content_center_admin_records($filters=array()){
    $records = array();
    $kw = trim((string)($filters['q'] ?? ''));
    $filterChannel = trim((string)($filters['channel'] ?? ''));
    $filterStatus = trim((string)($filters['status'] ?? ''));
    $filterScope = trim((string)($filters['scope'] ?? ''));
    foreach(content_center_all_files() as $file){
        $article = content_center_read_raw($file);
        if(!$article) continue;
        $article['article_id'] = $article['article_id'] ?? '';
        $article['title'] = $article['title'] ?? '';
        $article['status'] = $article['status'] ?? 'published';
        $article['publish_time'] = $article['publish_time'] ?? '';
        if($filterChannel !== '' && ($article['channel'] ?? '') !== $filterChannel) continue;
        if($filterStatus !== '' && ($article['status'] ?? '') !== $filterStatus) continue;
        if($filterScope !== '' && ($article['scope'] ?? '') !== $filterScope) continue;
        $haystack = implode(' ', array($article['article_id'] ?? '', $article['title'] ?? '', $article['summary'] ?? '', $article['filename'] ?? '', $article['target'] ?? '', $article['channel'] ?? '', $article['status'] ?? ''));
        if($kw !== ''){
            $ok = function_exists('mb_stripos') ? mb_stripos($haystack, $kw, 0, 'UTF-8') !== false : stripos($haystack, $kw) !== false;
            if(!$ok) continue;
        }
        $records[] = $article;
    }
    usort($records, function($a,$b){
        $ta = strtotime($a['updated_at'] ?? ($a['created_at'] ?? 0));
        $tb = strtotime($b['updated_at'] ?? ($b['created_at'] ?? 0));
        if(!$ta) $ta = intval($a['created_at'] ?? 0);
        if(!$tb) $tb = intval($b['created_at'] ?? 0);
        return $tb <=> $ta;
    });
    return $records;
}

function content_center_save_article($article, $scope, $target, $channel='news', $oldFile=''){
    $scope = in_array($scope, array('site','theme','global'), true) ? $scope : 'site';
    $channel = content_center_safe_key($channel ?: 'news');
    $target = $scope === 'global' ? 'all' : content_center_safe_key($target);
    $dir = content_center_build_dir($scope, $target, $channel);
    if(!is_dir($dir)) @mkdir($dir, 0777, true);
    $article['article_id'] = $article['article_id'] ?? ('CNT' . date('YmdHis') . mt_rand(100,999));
    $article['scope'] = $scope;
    $article['target'] = $target;
    $article['channel'] = $channel;
    $article['created_at'] = $article['created_at'] ?? time();
    $article['updated_at'] = date('Y-m-d H:i:s');
    $file = $dir . '/' . content_center_filename($article);
    $ok = file_put_contents($file, "<?php\nreturn " . var_export($article, true) . ";\n", LOCK_EX) !== false;
    if($ok && $oldFile && is_file($oldFile) && realpath($oldFile) !== realpath($file)) @unlink($oldFile);
    if($ok && function_exists('static_cache_clear')) static_cache_clear();
    if($ok) content_center_push_realtime($article);
    return $ok;
}

function content_center_delete_article($articleId){
    $file = content_center_find_file($articleId);
    if($file && is_file($file)){
        $root = str_replace('\\', '/', content_center_root());
        $path = str_replace('\\', '/', $file);
        $rel = ltrim(str_replace($root, '', $path), '/');
        $trash = content_center_trash_root() . '/' . $rel . '.' . date('YmdHis') . '.trash.php';
        if(!is_dir(dirname($trash))) @mkdir(dirname($trash), 0777, true);
        $ok = @rename($file, $trash);
        if($ok && function_exists('static_cache_clear')) static_cache_clear();
        return $ok;
    }
    return false;
}

function content_center_restore_article($trashFile){
    $trashRoot = realpath(content_center_trash_root());
    $real = realpath($trashFile);
    if(!$trashRoot || !$real || strpos($real, $trashRoot) !== 0 || !is_file($real)) return false;
    $article = content_center_read_raw($real);
    if(!$article) return false;
    $scope = $article['scope'] ?? 'site';
    $target = $article['target'] ?? '';
    $channel = $article['channel'] ?? 'news';
    $dir = content_center_build_dir($scope, $target, $channel);
    if(!is_dir($dir)) @mkdir($dir, 0777, true);
    $targetFile = $dir . '/' . content_center_filename($article);
    if(is_file($targetFile)) $targetFile = $dir . '/' . pathinfo($targetFile, PATHINFO_FILENAME) . '-' . date('His') . '.php';
    $ok = @rename($real, $targetFile);
    if($ok && function_exists('static_cache_clear')) static_cache_clear();
    return $ok;
}

function content_center_purge_trash_file($trashFile){
    $trashRoot = realpath(content_center_trash_root());
    $real = realpath($trashFile);
    if(!$trashRoot || !$real || strpos($real, $trashRoot) !== 0 || !is_file($real)) return false;
    return @unlink($real);
}

function content_center_format_publish_time($raw){
    $raw = trim((string)$raw);
    if($raw === '') return date('Y-m-d H:i:s');
    $normalized = str_replace('T', ' ', $raw);
    if(preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $normalized)) $normalized .= ':00';
    $ts = strtotime($normalized);
    return $ts ? date('Y-m-d H:i:s', $ts) : '';
}

function content_center_safe_html($html){
    $html = (string)$html;
    $allowed = '<p><br><strong><b><em><i><u><h2><h3><h4><ul><ol><li><blockquote><a><img><div><span>';
    $html = strip_tags($html, $allowed);
    $html = preg_replace('/\s+on\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html);
    $html = preg_replace('/javascript\s*:/i', '', $html);
    return $html;
}
