<?php

function current_site_dir(){
    $host = strtolower($_SERVER['HTTP_HOST'] ?? 'localhost');
    $host = explode(':', $host)[0];
    $candidates = array($host);
    if(strpos($host, 'www.') === 0){ $candidates[] = substr($host, 4); } else { $candidates[] = 'www.' . $host; }
    foreach($candidates as $h){
        $dir = __DIR__ . '/../data/sites/' . $h;
        if(is_dir($dir)) return $dir;
    }
    return null;
}
function parse_txt_article($file){
    if(!is_file($file)) return null;
    $raw = str_replace("\r\n", "\n", file_get_contents($file));
    $parts = explode("正文：", $raw, 2);
    $meta = $parts[0] ?? ''; $body = trim($parts[1] ?? '');
    $get = function($key) use ($meta){ if(preg_match('/^'.preg_quote($key,'/').'：(.*)$/mu', $meta, $m)) return trim($m[1]); return ''; };
    $id = intval(preg_replace('/\D+/', '', basename($file))); if($id<=0) $id=abs(crc32($file));
    $img=$get('图片'); if($img==='') $img=theme_asset_pick(current_site_theme(), basename(dirname($file)), basename($file));
    return array('id'=>$id,'title'=>$get('标题'),'date'=>$get('日期')?:date('Y-m-d',filemtime($file)),'type'=>$get('分类')?:'企业新闻','tags'=>array_filter(array_map('trim',explode(',',$get('关键词')))),'summary'=>$get('摘要'),'image'=>$img,'content'=>$body,'source_file'=>basename($file));
}

function theme_asset_pick($theme, $channel='news', $seed=''){
    $file = __DIR__ . '/../data/theme_assets.php';
    $assets = is_file($file) ? include $file : array();
    if(empty($assets[$theme])) return '';
    $pool = $assets[$theme][$channel] ?? ($assets[$theme]['news'] ?? array());
    if(!$pool) return '';
    $idx = $seed === '' ? array_rand($pool) : (abs(crc32($seed)) % count($pool));
    return $pool[$idx];
}
function current_site_theme(){
    $host = strtolower($_SERVER['HTTP_HOST'] ?? 'localhost');
    $host = explode(':', $host)[0];
    $domains = include __DIR__ . '/../config/domain.php';
    return $domains[$host]['theme'] ?? 'industrial';
}

function article_sort_time($item){
    if(!is_array($item)) return 0;
    foreach(array('publish_time', 'updated_at', 'created_at', 'date') as $field){
        if(empty($item[$field])) continue;
        if(is_numeric($item[$field])) return (int)$item[$field];
        $time = strtotime((string)$item[$field]);
        if($time) return $time;
    }
    return 0;
}

function article_sort_desc(&$items){
    if(!is_array($items)) return;
    usort($items, function($a, $b){
        $tb = article_sort_time($b);
        $ta = article_sort_time($a);
        if($tb === $ta){
            return intval($b['id'] ?? 0) <=> intval($a['id'] ?? 0);
        }
        return $tb <=> $ta;
    });
}

function txt_articles_load($channel){
    $items=array();
    $siteDir=current_site_dir();
    if($siteDir){
        $dir=$siteDir.'/'.$channel;
        if(is_dir($dir)){
            foreach(glob($dir.'/*.txt') as $file){ $item=parse_txt_article($file); if($item && $item['title']) $items[]=$item; }
        }
    }
    if(function_exists('content_center_load_articles')){
        $host = strtolower($_SERVER['HTTP_HOST'] ?? 'localhost');
        $host = explode(':', $host)[0];
        $items = array_merge($items, content_center_load_articles(current_site_theme(), $host, $channel));
    }
    article_sort_desc($items);
    return $items;
}

function article_content_render($item, $field='content'){
    $text = '';
    if(is_array($item)){
        $text = (string)($item[$field] ?? '');
        if($text === '' && $field === 'answer') $text = (string)($item['content'] ?? '');
    }
    $format = is_array($item) ? ($item['content_format'] ?? '') : '';
    if($format === 'html'){
        if(function_exists('content_center_safe_html')) return content_center_safe_html($text);
        return strip_tags($text, '<p><br><strong><b><em><i><u><h2><h3><h4><ul><ol><li><blockquote><a><img><div><span>');
    }
    return nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));
}

function detect_spider($ua){
    $uaLower=strtolower($ua);
    $map=array(
        'Baiduspider'=>array('baiduspider','baidu.com/search/spider.html','baidu spider','baidu-site-verification'),
        'Googlebot'=>array('googlebot'),
        'Bingbot'=>array('bingbot'),
        'YandexBot'=>array('yandex'),
        'Sogou'=>array('sogou'),
        '360Spider'=>array('360spider'),
        'Bytespider'=>array('bytespider'),
        'Shenma'=>array('shenma')
    );
    foreach($map as $name=>$needles){
        foreach($needles as $needle){
            if($needle !== '' && strpos($uaLower, strtolower($needle)) !== false) return $name;
        }
    }
    return '';
}
function spider_log_record(){
    $ua=$_SERVER['HTTP_USER_AGENT']??''; $spider=detect_spider($ua); if(!$spider) return;
    $host=strtolower($_SERVER['HTTP_HOST']??''); $ip=$_SERVER['HTTP_X_FORWARDED_FOR']??($_SERVER['REMOTE_ADDR']??''); if(strpos($ip,',')!==false) $ip=trim(explode(',',$ip)[0]);
    $url=$_SERVER['REQUEST_URI']??'/'; $line=date('Y-m-d H:i:s')."\t".$host."\t".$spider."\t".$ip."\t".$url."\t".str_replace(array("\r","\n","\t"),' ',$ua)."\n";
    $logDir=__DIR__.'/../cache/spider'; if(!is_dir($logDir)) @mkdir($logDir,0777,true); file_put_contents($logDir.'/spider.log',$line,FILE_APPEND|LOCK_EX);
}

function friend_links_load_config(){
    $file = __DIR__ . '/../config/links.php';
    $cfg = is_file($file) ? include $file : array();
    if(!is_array($cfg)) $cfg = array();
    // 兼容旧版：直接返回友链数组。
    if(isset($cfg[0]) && is_array($cfg[0])){
        $cfg = array('settings'=>array(), 'items'=>$cfg);
    }
    $settings = array_merge(array(
        'enabled' => 1,
        'home_count' => 15,
        'inner_min_count' => 3,
        'inner_max_count' => 6,
        'new_window' => 1,
        'nofollow' => 1,
        'auto_domain_links' => 1,
        'auto_protocol' => 'https',
    ), $cfg['settings'] ?? array());
    $items = $cfg['items'] ?? array();
    return array('settings'=>$settings, 'items'=>$items);
}


function friend_links_norm_host($host){
    $host = strtolower(trim((string)$host));
    $host = explode(':', $host)[0];
    return preg_replace('/^www\./i', '', $host);
}

function friend_links_build_auto_domain_items(){
    $domainFile = __DIR__ . '/../config/domain.php';
    $domainAutoFile = __DIR__ . '/../config/domain_auto.php';
    $companyFile = __DIR__ . '/../data/company.php';
    $profileFile = __DIR__ . '/../data/theme_profiles.php';
    $domains = is_file($domainFile) ? include $domainFile : array();
    $autoDomains = is_file($domainAutoFile) ? include $domainAutoFile : array();
    $companies = is_file($companyFile) ? include $companyFile : array();
    $profiles = is_file($profileFile) ? include $profileFile : array();
    if(!is_array($domains)) $domains = array();
    if(!is_array($autoDomains)) $autoDomains = array();
    if(!is_array($companies)) $companies = array();
    if(!is_array($profiles)) $profiles = array();

    $items = array();
    foreach(array($domains, $autoDomains) as $domainSet){
        foreach($domainSet as $domain=>$cfg){
            $domain = strtolower(trim((string)$domain));
            if($domain === '' || in_array($domain, array('localhost','127.0.0.1','::1'), true)) continue;
            if(!is_array($cfg)) continue;
            $theme = $cfg['theme'] ?? ($cfg['auto_profile_theme'] ?? 'industrial');
            $name = '';
            if(isset($cfg['short_name']) && trim((string)$cfg['short_name']) !== ''){
                $name = trim((string)$cfg['short_name']);
            }elseif(isset($cfg['name']) && trim((string)$cfg['name']) !== ''){
                $name = trim((string)$cfg['name']);
            }elseif(isset($cfg['company_name']) && trim((string)$cfg['company_name']) !== ''){
                $name = trim((string)$cfg['company_name']);
            }elseif(isset($cfg['company_id']) && isset($companies[$cfg['company_id']])){
                $company = $companies[$cfg['company_id']];
                $name = trim((string)($company['short_name'] ?? ($company['name'] ?? '')));
            }elseif(isset($cfg['auto_profile_theme'])){
                $profileTheme = $cfg['auto_profile_theme'];
                $profileIndex = intval($cfg['auto_profile_index'] ?? 0);
                $profile = $profiles[$profileTheme][$profileIndex] ?? null;
                if(is_array($profile)) $name = trim((string)($profile['short_name'] ?? ($profile['name'] ?? '')));
            }
            if($name === '') $name = $domain;
            $items[] = array(
                'enabled' => 1,
                'theme' => $theme,
                'weight' => max(1, min(10, intval($cfg['link_weight'] ?? ($cfg['weight'] ?? 1)))),
                'name' => $name,
                 // 自动友链
                'url' => 'http://' . $domain,
                'auto_domain' => 1,
            );
        }
    }
    return $items;
}

function friend_links_current_host(){
    $host = strtolower($_SERVER['HTTP_HOST'] ?? '');
    $host = explode(':', $host)[0];
    return friend_links_norm_host($host);
}

function friend_links_url_host($url){
    $host = parse_url((string)$url, PHP_URL_HOST);
    $host = strtolower((string)$host);
    return friend_links_norm_host($host);
}

function friend_links_is_homepage(){
    $path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
    $path = rtrim((string)$path, '/');
    return $path === '' || $path === '/index.php';
}

function friend_links_stable_shuffle($items, $seed){
    foreach($items as $k=>$item){
        $items[$k]['_sort'] = sprintf('%u', crc32($seed . '|' . ($item['url'] ?? '') . '|' . ($item['name'] ?? '') . '|' . $k));
    }
    usort($items, function($a,$b){
        if($a['_sort'] == $b['_sort']) return 0;
        return ($a['_sort'] < $b['_sort']) ? -1 : 1;
    });
    foreach($items as $k=>$item){ unset($items[$k]['_sort']); }
    return $items;
}

function friend_links_pick_items($cfg, $theme, $count){
    $host = friend_links_current_host();
    $pool = array();
    $allItems = $cfg['items'] ?? array();
    if(!empty($cfg['settings']['auto_domain_links'])){
        $allItems = array_merge($allItems, friend_links_build_auto_domain_items());
    }
    foreach($allItems as $item){
        if(empty($item['enabled'])) continue;
        if(trim((string)($item['name'] ?? '')) === '' || trim((string)($item['url'] ?? '')) === '') continue;
        if(($item['theme'] ?? '') !== $theme) continue;
        if(friend_links_url_host($item['url']) === $host) continue;
        $weight = max(1, min(10, intval($item['weight'] ?? 1)));
        for($i=0; $i<$weight; $i++){
            $copy = $item;
            $copy['_weight_slot'] = $i;
            $pool[] = $copy;
        }
    }
    $seed = $host . '|' . $theme . '|' . date('Ymd') . '|' . ($_SERVER['REQUEST_URI'] ?? '/');
    $pool = friend_links_stable_shuffle($pool, $seed);
    $picked = array();
    $seen = array();
    foreach($pool as $item){
        $key = friend_links_url_host($item['url']) ?: strtolower($item['url']);
        if(isset($seen[$key])) continue;
        unset($item['_weight_slot']);
        $picked[] = $item;
        $seen[$key] = true;
        if(count($picked) >= $count) break;
    }
    return $picked;
}

function render_auto_friend_links($customCount = null){
    global $theme;
    $cfg = friend_links_load_config();
    $settings = $cfg['settings'];
    if(empty($settings['enabled'])) return '';
    $isHome = friend_links_is_homepage();
    if($customCount !== null){
        $count = max(1, intval($customCount));
    }elseif($isHome){
        $count = max(1, intval($settings['home_count'] ?? 15));
    }else{
        $min = max(1, intval($settings['inner_min_count'] ?? 3));
        $max = max($min, intval($settings['inner_max_count'] ?? 6));
        $seed = friend_links_current_host() . '|' . date('Ymd') . '|' . ($_SERVER['REQUEST_URI'] ?? '/');
        $count = $min + (abs(crc32($seed)) % ($max - $min + 1));
    }
    $items = friend_links_pick_items($cfg, $theme ?: 'industrial', $count);
    if(!$items) return '';
    $target = !empty($settings['new_window']) ? ' target="_blank"' : '';
    $relParts = array('noopener');
    if(!empty($settings['nofollow'])) $relParts[] = 'nofollow';
    $rel = ' rel="' . e(implode(' ', $relParts)) . '"';
    $html = '<div class="container links"><strong>友情链接：</strong>';
    foreach($items as $l){
        $html .= '<a href="' . e($l['url']) . '"' . $target . $rel . '>' . e($l['name']) . '</a>';
    }
    $html .= '</div>';
    return $html;
}
