<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
admin_header('后台首页');

$sitesDir = __DIR__ . '/../data/sites';
$siteCount = is_dir($sitesDir) ? count(array_filter(glob($sitesDir.'/*'), 'is_dir')) : 0;
$spiderLog = __DIR__ . '/../cache/spider/spider.log';
$spiderCount = is_file($spiderLog) ? count(file($spiderLog, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) : 0;
$linkFile = __DIR__ . '/../config/links.php';
$linkCount = 0;
if(is_file($linkFile)){
    $links = include $linkFile;
    $linkCount = is_array($links) ? count($links) : 0;
}
$domainFile = __DIR__ . '/../config/domain.php';
$domainAutoFile = __DIR__ . '/../config/domain_auto.php';
$themeProfileFile = __DIR__ . '/../data/theme_profiles.php';
$domains = is_file($domainFile) ? include $domainFile : array();
$autoDomains = is_file($domainAutoFile) ? include $domainAutoFile : array();
$themeProfiles = is_file($themeProfileFile) ? include $themeProfileFile : array();
if(!is_array($domains)) $domains = array();
if(!is_array($autoDomains)) $autoDomains = array();
if(!is_array($themeProfiles)) $themeProfiles = array();

function home_domain_resolve_auto_theme($cfg){
    $theme = trim((string)($cfg['auto_profile_theme'] ?? ''));
    if($theme === '') $theme = trim((string)($cfg['theme'] ?? ''));
    return $theme;
}

function home_domain_distribution_rows($themes, $domains, $autoDomains, $themeProfiles){
    $stats = array();
    foreach($themes as $key=>$name){
        $stats[$key] = array('key'=>$key, 'name'=>$name, 'manual'=>0, 'auto'=>0, 'profiles'=>array());
    }
    foreach($domains as $domain=>$cfg){
        if(in_array($domain, array('localhost','127.0.0.1','::1'), true)) continue;
        $theme = trim((string)($cfg['theme'] ?? ''));
        if(isset($stats[$theme])) $stats[$theme]['manual']++;
    }
    foreach($autoDomains as $domain=>$cfg){
        if(in_array($domain, array('localhost','127.0.0.1','::1'), true)) continue;
        $theme = home_domain_resolve_auto_theme($cfg);
        if(!isset($stats[$theme])) continue;
        $stats[$theme]['auto']++;
        $idx = intval($cfg['auto_profile_index'] ?? -1);
        if($idx >= 0) $stats[$theme]['profiles'][$idx] = true;
    }
    $total = 0;
    foreach($stats as $row) $total += $row['manual'] + $row['auto'];
    $rows = array();
    foreach($stats as $key=>$row){
        $count = $row['manual'] + $row['auto'];
        $rows[] = array(
            'key'=>$key,
            'name'=>$row['name'],
            'manual'=>$row['manual'],
            'auto'=>$row['auto'],
            'total'=>$count,
            'percent'=>$total > 0 ? round($count * 100 / $total, 1) : 0,
            'profile_used'=>count($row['profiles']),
            'profile_total'=>count($themeProfiles[$key] ?? array()),
        );
    }
    usort($rows, function($a, $b){
        if($a['total'] === $b['total']) return strcmp($a['key'], $b['key']);
        return $b['total'] <=> $a['total'];
    });
    return array($rows, $total);
}

list($domainDistributionRows, $domainDistributionTotal) = home_domain_distribution_rows(admin_site_themes(), $domains, $autoDomains, $themeProfiles);
?>
<div class="grid">
    <div class="stat"><strong><?php echo $siteCount; ?></strong><span>域名内容目录</span></div>
    <div class="stat"><strong><?php echo $spiderCount; ?></strong><span>蜘蛛访问记录</span></div>
    <div class="stat"><strong><?php echo $linkCount; ?></strong><span>友情链接</span></div>
    <div class="stat"><strong>TXT</strong><span>文件内容模式</span></div>
</div>

<div class="card">
    <h2>域名分配统计</h2>
    <p class="help">共统计 <?php echo intval($domainDistributionTotal); ?> 个真实域名，展示全部主题并按占比从高到低排序。正式配置来自 <code>/config/domain.php</code>，自动配置来自 <code>/config/domain_auto.php</code>。</p>
    <div class="grid domain-home-stats">
        <?php foreach($domainDistributionRows as $row): ?>
        <div class="stat">
            <strong><?php echo intval($row['total']); ?> <small><?php echo admin_h($row['percent']); ?>%</small></strong>
            <span><?php echo admin_h($row['name']); ?> / <?php echo admin_h($row['key']); ?>：正式 <?php echo intval($row['manual']); ?> / 自动 <?php echo intval($row['auto']); ?> / 资料 <?php echo intval($row['profile_used']); ?><?php echo $row['profile_total'] ? '/' . intval($row['profile_total']) : ''; ?></span>
        </div>
        <?php endforeach; ?>
    </div>
    <p><a class="btn small" href="<?php echo admin_h(cms_admin_url('site_config.php')); ?>">查看站群管理</a></p>
</div>

<?php
$account = admin_client_account();
$licenseStatus = license_status();
$onlineCache = function_exists('license_cache_read') ? license_cache_read() : array();
$licenseData = $licenseStatus['data'] ?? array();
?>
<div class="card">
    <h2>用户信息</h2>
    <div class="info-grid">
        <div><span>当前账号</span><strong><?php echo admin_h(admin_current_account_name()); ?></strong></div>
        <div><span>客户名称</span><strong><?php echo admin_h($account['name'] ?? '未注册'); ?></strong></div>
        <div><span>联系人</span><strong><?php echo admin_h($account['contact'] ?? '-'); ?></strong></div>
        <div><span>客户ID</span><strong><?php echo admin_h(($account['customer_id'] ?? '') ?: ($licenseData['customer_id'] ?? '-')); ?></strong></div>
        <div><span>注册时间</span><strong><?php echo admin_h(admin_account_registered_at()); ?></strong></div>
    </div>
</div>

<div class="card">
    <h2>授权时间</h2>
    <div class="info-grid">
        <div><span>授权状态</span><strong><?php echo admin_h(function_exists('license_effective_status') ? license_status_label(license_effective_status()) : $licenseStatus['message']); ?></strong></div>
        <div><span>授权版本</span><strong><?php echo admin_h(($onlineCache['version'] ?? '') ?: ($licenseData['version'] ?? '-')); ?></strong></div>
        <div><span>授权到期</span><strong><?php echo admin_h(($onlineCache['expire_time'] ?? '') ?: ($licenseData['expire_time'] ?? '-')); ?></strong></div>
        <div><span>授权签发</span><strong><?php echo admin_h($licenseData['issued_at'] ?? '-'); ?></strong></div>
        <div><span>域名额度</span><strong><?php echo intval($licenseStatus['domain_count']); ?> / <?php echo admin_h(($onlineCache['site_limit'] ?? '') ?: ($licenseData['site_limit'] ?? '-')); ?></strong></div>
    </div>
    <p><a class="btn small" href="<?php echo admin_h(cms_admin_url('license.php')); ?>">查看授权</a></p>
</div>

<div class="card">
    <h2>后台说明</h2>
    <p>当前后台为轻量文件版，不依赖 MySQL，适合先期维护企业站内容、观察蜘蛛访问、管理友情链接。</p>
    <div class="warn">上线前请修改默认后台账号密码，并限制 /yanscms/ 访问来源。</div>
</div>

<?php if(function_exists('license_effective_status') && license_effective_status() !== 'active'): ?>
<div class="warn">
    <strong>后台核心功能限制状态：</strong>
    <?php echo admin_h(license_status_label(license_effective_status())); ?>。
    当前仅建议访问授权页、蜘蛛统计、操作日志等基础页面。
    <a class="btn small" href="<?php echo admin_h(cms_admin_url('license.php')); ?>">立即处理授权</a>
</div>
<?php endif; ?>

<?php admin_footer(); ?>
