<?php
include __DIR__ . '/auth.php';
admin_check();
include __DIR__ . '/layout.php';
include __DIR__ . '/config_writer.php';

$domainFile = __DIR__ . '/../config/domain.php';
$companyFile = __DIR__ . '/../data/company.php';
$extraFile = __DIR__ . '/../data/company_extra.php';
$domainAutoFile = __DIR__ . '/../config/domain_auto.php';
$themeProfileFile = __DIR__ . '/../data/theme_profiles.php';

$domains = is_file($domainFile) ? include $domainFile : array();
$companies = is_file($companyFile) ? include $companyFile : array();
$extras = is_file($extraFile) ? include $extraFile : array();
$autoDomains = is_file($domainAutoFile) ? include $domainAutoFile : array();
$themeProfiles = is_file($themeProfileFile) ? include $themeProfileFile : array();
if(!is_array($domains)) $domains = array();
if(!is_array($companies)) $companies = array();
if(!is_array($extras)) $extras = array();
if(!is_array($autoDomains)) $autoDomains = array();
if(!is_array($themeProfiles)) $themeProfiles = array();

$themes = admin_site_themes();
$message = '';
$error = '';

function site_config_norm_domain($domain){
    $domain = trim(strtolower((string)$domain));
    $domain = preg_replace('#^https?://#', '', $domain);
    $domain = preg_replace('#/.*$#', '', $domain);
    return explode(':', $domain)[0];
}

function site_config_valid_domain($domain){
    if(!$domain) return false;
    if(in_array($domain, array('localhost','127.0.0.1'), true)) return true;
    return (bool)preg_match('/^(?:[a-z0-9-]+\.)+[a-z]{2,}$/i', $domain);
}

function site_config_next_company_id($companies){
    $ids = array_map('intval', array_keys($companies));
    return $ids ? max($ids) + 1 : 1;
}

function site_config_create_site_dirs($domain){
    $base = __DIR__ . '/../data/sites/' . $domain;
    foreach(array('news','product','case','faq') as $dir){
        if(!is_dir($base . '/' . $dir)) @mkdir($base . '/' . $dir, 0777, true);
    }
}

function site_config_match_keyword($haystack, $keyword){
    $keyword = trim((string)$keyword);
    if($keyword === '') return true;
    if(function_exists('mb_stripos')) return mb_stripos($haystack, $keyword, 0, 'UTF-8') !== false;
    return stripos($haystack, $keyword) !== false;
}

function site_config_paginate($items, $page, $pageSize){
    $total = count($items);
    $pageSize = max(10, min(200, intval($pageSize)));
    $pages = max(1, (int)ceil($total / $pageSize));
    $page = max(1, min($pages, intval($page)));
    return array(array_slice($items, ($page - 1) * $pageSize, $pageSize, true), $total, $pages, $page, $pageSize);
}

function site_config_parse_batch_line($line, $defaultCity, $defaultCompany, $defaultTheme){
    $line = trim((string)$line);
    if($line === '' || strpos($line, '#') === 0) return null;
    $parts = preg_split('/\s*(?:---|\|)\s*|\t+/u', $line);
    return array(
        'domain' => site_config_norm_domain($parts[0] ?? ''),
        'city' => trim($parts[1] ?? $defaultCity),
        'company_name' => trim($parts[2] ?? $defaultCompany),
        'theme' => trim($parts[3] ?? $defaultTheme),
        'phone' => trim($parts[4] ?? ''),
        'icp' => trim($parts[5] ?? ''),
        'address' => trim($parts[6] ?? ''),
    );
}

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

function site_config_export_auto_domains($file, $data){
    if(function_exists('admin_backup_file')) admin_backup_file($file);
    $content = "<?php\n// 系统自动生成：未在 config/domain.php 配置的访问域名会自动分配主题和资料。\nreturn " . var_export($data, true) . ";\n";
    $ok = file_put_contents($file, $content, LOCK_EX) !== false;
    if($ok && function_exists('static_cache_clear')) static_cache_clear();
    return $ok;
}


function site_config_theme_description($companyName, $theme, $themes, $city='', $domain=''){
    $industry = $themes[$theme] ?? '企业服务';
    $map = array(
        'industrial'=>'围绕自动化产线、设备改造、现场交付和维保响应，服务制造企业的稳定生产与效率提升。',
        'education'=>'围绕课程设计、教学管理、学员服务和企业培训落地，提供更贴近真实学习目标的教育支持。',
        'construction'=>'围绕工程施工、项目协同、质量安全和交付节点，提供从方案到现场的持续工程服务。',
        'tech'=>'围绕系统建设、数据协同、业务流程和运维交付，帮助企业搭建稳定可持续的数字化能力。',
        'legal'=>'围绕合同审查、企业合规、劳动用工和经营风险，提供清晰审慎的法律咨询支持。',
        'finance'=>'围绕财税合规、账务梳理、经营分析和风险提示，为企业提供稳健的财务管理支持。',
        'logistics'=>'围绕仓配协同、运输调度、节点追踪和交付稳定，提升货物流转的可视化与可控性。',
        'agriculture'=>'围绕基地管理、农产品品质、供应链组织和数字化记录，服务农业项目的长期运营。',
        'tourism'=>'围绕线路策划、目的地运营、客户体验和活动执行，打造更有秩序的文旅服务流程。',
        'interior'=>'围绕空间规划、材料搭配、施工衔接和交付细节，提供兼顾审美与实用的室内设计服务。',
        'sports'=>'围绕训练组织、赛事活动、场馆运营和用户体验，提供专业稳定的体育服务支持。',
        'game'=>'围绕游戏研发、发行运营、电竞活动和玩家社区，提供更稳定的互动娱乐服务支持。',
        'live'=>'围绕直播运营、主播孵化、活动执行和数据复盘，提供更清晰的内容转化服务支持。',
        'school'=>'围绕课程建设、学生成长、校园管理和家校沟通，建设有秩序、有温度的学习环境。',
    );
    $region = trim((string)$city) !== '' ? trim((string)$city) . '及周边区域' : '本地及周边区域';
    $domainPart = trim((string)$domain) !== '' ? '当前站点 ' . trim((string)$domain) . ' 聚焦展示企业能力、服务范围与项目经验，' : '';
    return $companyName . '立足' . $region . '，专注' . $industry . '相关服务。' . $domainPart . ($map[$theme] ?? '围绕客户真实需求、项目执行、长期维护和本地化响应，提供稳定清晰的服务支持。') . '团队注重需求沟通、过程反馈和交付复盘，帮助客户在预算、周期、质量和后续维护之间取得更稳妥的平衡。';
}
function site_config_company_template($companyName, $theme, $themes, $city, $phone='', $icp='', $address=''){
    $industry = $themes[$theme] ?? '企业服务';
    return array(
        'name' => $companyName,
        'short_name' => function_exists('mb_substr') ? mb_substr($companyName, 0, 4, 'UTF-8') : substr($companyName, 0, 12),
        'industry' => $industry,
        'city' => $city ?: '本地',
        'title' => $companyName,
        'keywords' => $industry . ',企业服务,本地服务,项目服务',
        'description' => site_config_theme_description($companyName, $theme, $themes, $city),
        'slogan' => '围绕真实需求，提供长期稳定服务',
        'phone' => $phone,
        'email' => '',
        'address' => $address,
        'icp' => $icp,
        'banner' => '/assets/uploads/banner/banner-' . $theme . '.jpg',
        'about_image' => '/assets/uploads/company/company-' . $theme . '.jpg',
    );
}

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $action = $_POST['action'] ?? '';

    if($action === 'add_domain'){
        $domain = site_config_norm_domain($_POST['domain'] ?? '');
        $theme = $_POST['theme'] ?? 'industrial';
        $companyName = trim($_POST['company_name'] ?? '');
        $city = trim($_POST['city'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $icp = trim($_POST['icp'] ?? '');
        $address = trim($_POST['address'] ?? '');
        if(!site_config_valid_domain($domain)){
            $error = '域名格式不正确。';
        }elseif(isset($domains[$domain])){
            $error = '该域名已存在。';
        }elseif(!isset($themes[$theme])){
            $error = '主题无效。';
        }elseif($companyName === ''){
            $error = '企业名称不能为空。';
        }else{
            $cid = site_config_next_company_id($companies);
            $domains[$domain] = array('company_id'=>$cid, 'theme'=>$theme);
            $companies[$cid] = site_config_company_template($companyName, $theme, $themes, $city, $phone, $icp, $address);
            admin_export_php($domainFile, $domains);
            admin_export_php($companyFile, $companies);
            site_config_create_site_dirs($domain);
            if(function_exists('admin_oplog')) admin_oplog('add_domain', $domain);
            $message = '新增域名成功：' . $domain;
        }
    }

    if($action === 'batch_add_domains'){
        $defaultTheme = $_POST['bulk_theme'] ?? 'industrial';
        $defaultCity = trim($_POST['bulk_city'] ?? '本地');
        $defaultCompany = trim($_POST['bulk_company_name'] ?? '企业服务有限公司');
        $lines = preg_split('/\r\n|\r|\n/', trim($_POST['bulk_domains'] ?? ''));
        $added = 0;
        $skipped = array();
        foreach($lines as $line){
            $row = site_config_parse_batch_line($line, $defaultCity, $defaultCompany, $defaultTheme);
            if(!$row || $row['domain'] === '') continue;
            $domain = $row['domain'];
            $theme = isset($themes[$row['theme']]) ? $row['theme'] : $defaultTheme;
            if(!site_config_valid_domain($domain)){ $skipped[] = $domain . '（格式无效）'; continue; }
            if(isset($domains[$domain])){ $skipped[] = $domain . '（已存在）'; continue; }
            $cid = site_config_next_company_id($companies);
            $domains[$domain] = array('company_id'=>$cid, 'theme'=>$theme);
            $companies[$cid] = site_config_company_template($row['company_name'] ?: $defaultCompany, $theme, $themes, $row['city'], $row['phone'], $row['icp'], $row['address']);
            site_config_create_site_dirs($domain);
            $added++;
        }
        if($added > 0){
            admin_export_php($domainFile, $domains);
            admin_export_php($companyFile, $companies);
            if(function_exists('admin_oplog')) admin_oplog('batch_add_domains', 'count=' . $added);
        }
        $message = '批量添加完成：新增 ' . $added . ' 个域名';
        if($skipped) $message .= '；跳过：' . implode('、', array_slice($skipped, 0, 8)) . (count($skipped) > 8 ? ' 等' : '');
    }

    if($action === 'update_domain'){
        $oldDomain = site_config_norm_domain($_POST['old_domain'] ?? '');
        $newDomain = site_config_norm_domain($_POST['domain'] ?? '');
        if(!isset($domains[$oldDomain])){
            $error = '原域名不存在。';
        }elseif(!site_config_valid_domain($newDomain)){
            $error = '新域名格式不正确。';
        }elseif($newDomain !== $oldDomain && isset($domains[$newDomain])){
            $error = '新域名已存在。';
        }else{
            $cid = intval($domains[$oldDomain]['company_id'] ?? ($_POST['company_id'] ?? 0));
            $theme = isset($themes[$_POST['theme'] ?? '']) ? $_POST['theme'] : ($domains[$oldDomain]['theme'] ?? 'industrial');
            $company = $companies[$cid] ?? array();
            $company['name'] = trim($_POST['company_name'] ?? ($company['name'] ?? ''));
            $company['short_name'] = trim($_POST['short_name'] ?? ($company['short_name'] ?? ''));
            $company['industry'] = trim($_POST['industry'] ?? ($company['industry'] ?? ''));
            $company['city'] = trim($_POST['city'] ?? ($company['city'] ?? ''));
            $company['phone'] = trim($_POST['phone'] ?? ($company['phone'] ?? ''));
            $company['email'] = trim($_POST['email'] ?? ($company['email'] ?? ''));
            $company['icp'] = trim($_POST['icp'] ?? ($company['icp'] ?? ''));
            $company['address'] = trim($_POST['address'] ?? ($company['address'] ?? ''));
            $company['title'] = trim($_POST['title'] ?? ($company['title'] ?? $company['name']));
            $company['keywords'] = trim($_POST['keywords'] ?? ($company['keywords'] ?? ''));
            $company['description'] = trim($_POST['description'] ?? ($company['description'] ?? ''));
            $company['slogan'] = trim($_POST['slogan'] ?? ($company['slogan'] ?? ''));
            $company['banner'] = trim($_POST['banner'] ?? ($company['banner'] ?? ''));
            $company['about_image'] = trim($_POST['about_image'] ?? ($company['about_image'] ?? ''));
            if($company['name'] === ''){
                $error = '企业名称不能为空。';
            }else{
                if($newDomain !== $oldDomain){
                    $domains[$newDomain] = $domains[$oldDomain];
                    unset($domains[$oldDomain]);
                    $oldDir = __DIR__ . '/../data/sites/' . $oldDomain;
                    $newDir = __DIR__ . '/../data/sites/' . $newDomain;
                    if(is_dir($oldDir) && !is_dir($newDir)) @rename($oldDir, $newDir);
                }
                $domains[$newDomain]['company_id'] = $cid;
                $domains[$newDomain]['theme'] = $theme;
                $companies[$cid] = $company;
                admin_export_php($domainFile, $domains);
                admin_export_php($companyFile, $companies);
                site_config_create_site_dirs($newDomain);
                if(function_exists('admin_oplog')) admin_oplog('update_domain', $oldDomain . ' => ' . $newDomain);
                $message = '域名配置已更新：' . $newDomain;
            }
        }
    }

    if($action === 'delete_domain' || $action === 'bulk_delete_domain'){
        $selected = $action === 'delete_domain' ? array($_POST['domain'] ?? '') : ($_POST['domains'] ?? array());
        $deleted = 0;
        foreach($selected as $rawDomain){
            $domain = site_config_norm_domain($rawDomain);
            if(!$domain || !isset($domains[$domain]) || in_array($domain, array('localhost','127.0.0.1'), true)) continue;
            $cid = intval($domains[$domain]['company_id'] ?? 0);
            unset($domains[$domain]);
            $stillUsed = false;
            foreach($domains as $cfg){
                if(intval($cfg['company_id'] ?? 0) === $cid){ $stillUsed = true; break; }
            }
            if($cid && !$stillUsed && isset($companies[$cid])) unset($companies[$cid]);
            $deleted++;
        }
        if($deleted > 0){
            admin_export_php($domainFile, $domains);
            admin_export_php($companyFile, $companies);
            if(function_exists('admin_oplog')) admin_oplog($action, 'count=' . $deleted);
            $message = '已删除域名配置：' . $deleted . ' 条';
        }else{
            $error = '没有可删除的域名配置。';
        }
    }

    if($action === 'clear_domain_list'){
        $clearQ = trim((string)($_POST['clear_q'] ?? ''));
        $clearTheme = trim((string)($_POST['clear_theme'] ?? ''));
        $selected = array();
        foreach($domains as $domain=>$cfg){
            if(in_array($domain, array('localhost','127.0.0.1'), true)) continue;
            $cid = intval($cfg['company_id'] ?? 0);
            $company = $companies[$cid] ?? array();
            $themeKey = $cfg['theme'] ?? '';
            $haystack = $domain . ' ' . $cid . ' ' . $themeKey . ' ' . implode(' ', array($company['name'] ?? '', $company['short_name'] ?? '', $company['city'] ?? '', $company['phone'] ?? '', $company['icp'] ?? '', $company['industry'] ?? ''));
            if($clearTheme !== '' && $themeKey !== $clearTheme) continue;
            if(!site_config_match_keyword($haystack, $clearQ)) continue;
            $selected[] = $domain;
        }
        $deleted = 0;
        foreach($selected as $domain){
            if(!isset($domains[$domain])) continue;
            $cid = intval($domains[$domain]['company_id'] ?? 0);
            unset($domains[$domain]);
            $stillUsed = false;
            foreach($domains as $cfg){
                if(intval($cfg['company_id'] ?? 0) === $cid){ $stillUsed = true; break; }
            }
            if($cid && !$stillUsed && isset($companies[$cid])) unset($companies[$cid]);
            $deleted++;
        }
        if($deleted > 0){
            admin_export_php($domainFile, $domains);
            admin_export_php($companyFile, $companies);
            if(function_exists('admin_oplog')) admin_oplog('clear_domain_list', 'count=' . $deleted);
            $message = '已清空当前筛选下的域名配置：' . $deleted . ' 条';
        }else{
            $error = '当前筛选下没有可清空的域名配置。';
        }
    }

    if($action === 'delete_auto_domain'){
        $domain = site_config_norm_domain($_POST['domain'] ?? '');
        if(isset($autoDomains[$domain])){
            unset($autoDomains[$domain]);
            site_config_export_auto_domains($domainAutoFile, $autoDomains);
            if(function_exists('admin_oplog')) admin_oplog('delete_auto_domain', $domain);
            $message = '自动分配记录已删除：' . $domain;
        }else{
            $error = '自动分配记录不存在。';
        }
    }

    if($action === 'bulk_delete_auto_domain'){
        $selected = $_POST['domains'] ?? array();
        if(!is_array($selected)) $selected = array();
        $deleted = 0;
        foreach($selected as $rawDomain){
            $domain = site_config_norm_domain($rawDomain);
            if($domain && isset($autoDomains[$domain])){
                unset($autoDomains[$domain]);
                $deleted++;
            }
        }
        if($deleted > 0){
            site_config_export_auto_domains($domainAutoFile, $autoDomains);
            if(function_exists('admin_oplog')) admin_oplog('bulk_delete_auto_domain', 'count=' . $deleted);
            $message = '已删除自动分配记录：' . $deleted . ' 条';
        }else{
            $error = '没有可删除的自动分配记录。';
        }
    }

    if($action === 'clear_auto_domain_list'){
        $clearQ = trim((string)($_POST['clear_q'] ?? ''));
        $clearTheme = trim((string)($_POST['clear_theme'] ?? ''));
        $selected = array();
        foreach($autoDomains as $domain=>$cfg){
            $themeKey = site_config_resolve_auto_theme($cfg);
            $profileTheme = site_config_resolve_auto_theme($cfg);
            $profileIndex = intval($cfg['auto_profile_index'] ?? 0);
            $profile = $themeProfiles[$profileTheme][$profileIndex] ?? array();
            $haystack = $domain . ' ' . $themeKey . ' ' . $profileTheme . ' ' . $profileIndex . ' ' . implode(' ', array($profile['name'] ?? '', $profile['short_name'] ?? '', $profile['city'] ?? '', $profile['phone'] ?? '', $profile['icp'] ?? '', $profile['industry'] ?? ''));
            if($clearTheme !== '' && $themeKey !== $clearTheme) continue;
            if(!site_config_match_keyword($haystack, $clearQ)) continue;
            $selected[] = $domain;
        }
        $deleted = 0;
        foreach($selected as $domain){
            if(isset($autoDomains[$domain])){
                unset($autoDomains[$domain]);
                $deleted++;
            }
        }
        if($deleted > 0){
            site_config_export_auto_domains($domainAutoFile, $autoDomains);
            if(function_exists('admin_oplog')) admin_oplog('clear_auto_domain_list', 'count=' . $deleted);
            $message = '已清空当前筛选下的自动分配记录：' . $deleted . ' 条';
        }else{
            $error = '当前筛选下没有可清空的自动分配记录。';
        }
    }

    if($action === 'promote_auto_domain'){
        $domain = site_config_norm_domain($_POST['domain'] ?? '');
        if(!isset($autoDomains[$domain])){
            $error = '自动分配记录不存在。';
        }elseif(isset($domains[$domain])){
            $error = '该域名已存在正式配置。';
        }else{
            $autoCfg = $autoDomains[$domain];
            $theme = $autoCfg['theme'] ?? ($autoCfg['auto_profile_theme'] ?? 'industrial');
            $profileTheme = $autoCfg['auto_profile_theme'] ?? $theme;
            $profileIndex = intval($autoCfg['auto_profile_index'] ?? 0);
            $profile = $themeProfiles[$profileTheme][$profileIndex] ?? array();
            $cid = site_config_next_company_id($companies);
            $domains[$domain] = array('company_id'=>$cid, 'theme'=>$theme);
            $companies[$cid] = array_merge(site_config_company_template(($profile['name'] ?? $domain), $theme, $themes, ($profile['city'] ?? '本地')), $profile);
            unset($autoDomains[$domain]);
            admin_export_php($domainFile, $domains);
            admin_export_php($companyFile, $companies);
            site_config_export_auto_domains($domainAutoFile, $autoDomains);
            site_config_create_site_dirs($domain);
            if(function_exists('admin_oplog')) admin_oplog('promote_auto_domain', $domain);
            $message = '已转为正式配置：' . $domain;
        }
    }
}

$domains = is_file($domainFile) ? include $domainFile : array();
$companies = is_file($companyFile) ? include $companyFile : array();
$autoDomains = is_file($domainAutoFile) ? include $domainAutoFile : array();
$themeProfiles = is_file($themeProfileFile) ? include $themeProfileFile : array();
if(!is_array($domains)) $domains = array();
if(!is_array($companies)) $companies = array();
if(!is_array($autoDomains)) $autoDomains = array();
if(!is_array($themeProfiles)) $themeProfiles = array();

$editDomain = site_config_norm_domain($_GET['edit'] ?? '');
$editCfg = $editDomain && isset($domains[$editDomain]) ? $domains[$editDomain] : null;
$editCompany = array();
if($editCfg){
    $editCompany = $companies[intval($editCfg['company_id'] ?? 0)] ?? array();
}

$q = trim($_GET['q'] ?? '');
$themeFilter = trim($_GET['theme'] ?? '');
$typeFilter = trim($_GET['type'] ?? 'manual');
$pageSize = intval($_GET['page_size'] ?? 50);
$page = intval($_GET['page'] ?? 1);
$currentTab = $_GET['tab'] ?? '';
if($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'batch_add_domains') $currentTab = 'batch';
if(!in_array($currentTab, array('manage','batch'), true)) $currentTab = 'manage';

$manualRows = array();
foreach(array_reverse($domains, true) as $domain=>$cfg){
    if(in_array($domain, array('localhost','127.0.0.1'), true)) continue;
    $cid = intval($cfg['company_id'] ?? 0);
    $company = $companies[$cid] ?? array();
    $themeKey = $cfg['theme'] ?? '';
    $haystack = $domain . ' ' . $cid . ' ' . $themeKey . ' ' . implode(' ', array($company['name'] ?? '', $company['short_name'] ?? '', $company['city'] ?? '', $company['phone'] ?? '', $company['icp'] ?? '', $company['industry'] ?? ''));
    if($themeFilter !== '' && $themeKey !== $themeFilter) continue;
    if(!site_config_match_keyword($haystack, $q)) continue;
    $manualRows[$domain] = array('cfg'=>$cfg,'cid'=>$cid,'company'=>$company,'theme'=>$themeKey);
}
list($manualPageRows, $manualTotal, $manualPages, $manualPage, $manualPageSize) = site_config_paginate($manualRows, $page, $pageSize);

$autoRows = array();
foreach(array_reverse($autoDomains, true) as $domain=>$cfg){
    $themeKey = site_config_resolve_auto_theme($cfg);
    $profileTheme = site_config_resolve_auto_theme($cfg);
    $profileIndex = intval($cfg['auto_profile_index'] ?? 0);
    $profile = $themeProfiles[$profileTheme][$profileIndex] ?? array();
    $haystack = $domain . ' ' . $themeKey . ' ' . $profileTheme . ' ' . $profileIndex . ' ' . implode(' ', array($profile['name'] ?? '', $profile['short_name'] ?? '', $profile['city'] ?? '', $profile['phone'] ?? '', $profile['icp'] ?? '', $profile['industry'] ?? ''));
    if($themeFilter !== '' && $themeKey !== $themeFilter) continue;
    if(!site_config_match_keyword($haystack, $q)) continue;
    $autoRows[$domain] = array('cfg'=>$cfg,'profile'=>$profile,'theme'=>$themeKey,'profile_theme'=>$profileTheme,'profile_index'=>$profileIndex);
}
list($autoPageRows, $autoTotal, $autoPages, $autoPage, $autoPageSize) = site_config_paginate($autoRows, $page, $pageSize);

function site_config_page_url($pageNo){
    $params = $_GET;
    $params['page'] = $pageNo;
    return cms_admin_url('site_config.php') . '?' . http_build_query($params);
}

admin_header('站群管理');
?>
<?php if($message): ?><div class="notice"><?php echo admin_h($message); ?></div><?php endif; ?>
<?php if($error): ?><div class="error"><?php echo admin_h($error); ?></div><?php endif; ?>

<div class="cc-subnav">
    <a class="<?php echo $currentTab === 'manage' ? 'active' : ''; ?>" href="<?php echo admin_h(cms_admin_url('site_config.php')); ?>">站群管理</a>
    <a class="<?php echo $currentTab === 'batch' ? 'active' : ''; ?>" href="<?php echo admin_h(cms_admin_url('site_config.php') . '?tab=batch'); ?>">批量添加域名</a>
</div>

<div class="card">
<h2>站群管理与基础配置</h2>
<p>这里统一维护单个域名、批量域名、企业信息与主题绑定。域名分配统计已移动到后台首页，便于进入后台后先查看整体分布。</p>
</div>

<?php if($currentTab === 'manage'): ?>
<?php if($editCfg): ?>
<div class="card">
<h2>编辑域名配置：<?php echo admin_h($editDomain); ?></h2>
<form method="post" class="config-form">
<input type="hidden" name="action" value="update_domain">
<input type="hidden" name="old_domain" value="<?php echo admin_h($editDomain); ?>">
<input type="hidden" name="company_id" value="<?php echo intval($editCfg['company_id'] ?? 0); ?>">
<div class="form-grid">
<label>域名<input name="domain" value="<?php echo admin_h($editDomain); ?>"></label>
<label>主题<select name="theme"><?php foreach($themes as $key=>$name): ?><option value="<?php echo admin_h($key); ?>" <?php echo (($editCfg['theme'] ?? '')===$key?'selected':''); ?>><?php echo admin_h($name . ' / ' . $key); ?></option><?php endforeach; ?></select></label>
<label>企业名称<input name="company_name" value="<?php echo admin_h($editCompany['name'] ?? ''); ?>"></label>
<label>企业简称<input name="short_name" value="<?php echo admin_h($editCompany['short_name'] ?? ''); ?>"></label>
<label>行业名称<input name="industry" value="<?php echo admin_h($editCompany['industry'] ?? ''); ?>"></label>
<label>城市<input name="city" value="<?php echo admin_h($editCompany['city'] ?? ''); ?>"></label>
<label>电话<input name="phone" value="<?php echo admin_h($editCompany['phone'] ?? ''); ?>"></label>
<label>邮箱<input name="email" value="<?php echo admin_h($editCompany['email'] ?? ''); ?>"></label>
<label>备案号<input name="icp" value="<?php echo admin_h($editCompany['icp'] ?? ''); ?>"></label>
</div>
<label>地址<input name="address" value="<?php echo admin_h($editCompany['address'] ?? ''); ?>"></label>
<label>Title<input name="title" value="<?php echo admin_h($editCompany['title'] ?? ''); ?>"></label>
<label>Keywords<input name="keywords" value="<?php echo admin_h($editCompany['keywords'] ?? ''); ?>"></label>
<label>Description<textarea name="description" class="domain-desc-textarea"><?php echo admin_h($editCompany['description'] ?? ''); ?></textarea></label>
<label>Slogan<input name="slogan" value="<?php echo admin_h($editCompany['slogan'] ?? ''); ?>"></label>
<div class="form-grid two">
<label>Banner 图片<input name="banner" value="<?php echo admin_h($editCompany['banner'] ?? ''); ?>"></label>
<label>关于我们图片<input name="about_image" value="<?php echo admin_h($editCompany['about_image'] ?? ''); ?>"></label>
</div>
<p><button>保存修改</button> <a class="btn ghost" href="<?php echo admin_h(cms_admin_url('site_config.php')); ?>">取消编辑</a></p>
</form>
</div>
<?php endif; ?>

<div class="card">
<h2>添加新域名</h2>
<form method="post" class="config-form">
<input type="hidden" name="action" value="add_domain">
<div class="form-grid">
<label>域名<input name="domain" placeholder="www.example.com"></label>
<label>主题<select name="theme"><?php foreach($themes as $key=>$name): ?><option value="<?php echo admin_h($key); ?>"><?php echo admin_h($name . ' / ' . $key); ?></option><?php endforeach; ?></select></label>
<label>企业名称<input name="company_name" placeholder="某某企业服务有限公司"></label>
<label>城市<input name="city" placeholder="例如：深圳"></label>
<label>电话<input name="phone" placeholder="例如：0755-88888888"></label>
<label>备案号<input name="icp" placeholder="例如：粤ICP备2024000000号"></label>
<label>地址<input name="address" placeholder="例如：深圳市南山区某某路88号"></label>
</div>
<p><button>保存并创建域名目录</button></p>
</form>
</div>

<?php endif; ?>
<?php if($currentTab === 'batch'): ?>
<div class="card">
<h2>批量添加域名</h2>
<p class="domain-line-help">每行一个域名，支持：<code>域名---城市---企业名称---主题标识---电话---备案号---地址</code>。只写域名时使用下方默认城市、企业名称和主题。</p>
<form method="post" action="<?php echo admin_h(cms_admin_url('site_config.php') . '?tab=batch'); ?>" class="config-form">
<input type="hidden" name="action" value="batch_add_domains">
<div class="form-grid">
<label>默认主题<select name="bulk_theme"><?php foreach($themes as $key=>$name): ?><option value="<?php echo admin_h($key); ?>"><?php echo admin_h($name . ' / ' . $key); ?></option><?php endforeach; ?></select></label>
<label>默认城市<input name="bulk_city" placeholder="例如：深圳"></label>
<label>默认企业名称<input name="bulk_company_name" placeholder="例如：某某科技有限公司"></label>
</div>
<label>域名列表<textarea name="bulk_domains" rows="10" placeholder="www.a.com---深圳---某某科技有限公司---tech---0755-88888888---粤ICP备2024000000号---深圳市南山区&#10;www.b.com---广州---某某商务有限公司---finance&#10;www.c.com"></textarea></label>
<p><button>批量创建域名</button></p>
</form>
</div>
<?php endif; ?>

<?php if($currentTab === 'manage'): ?>
<div class="card">
<h2>域名配置总览</h2>
<p class="help">支持按域名、名称、城市、电话、备案号、company_id 搜索，并支持主题筛选与分页。</p>
<form method="get" class="config-form search-bar">
<div class="form-grid">
<label>关键词搜索<input name="q" value="<?php echo admin_h($q); ?>" placeholder="域名 / 名称 / 城市 / 电话 / 备案号 / company_id"></label>
<label>主题筛选<select name="theme"><option value="">全部主题</option><?php foreach($themes as $key=>$name): ?><option value="<?php echo admin_h($key); ?>" <?php echo $themeFilter===$key?'selected':''; ?>><?php echo admin_h($name . ' / ' . $key); ?></option><?php endforeach; ?></select></label>
<label>数据类型<select name="type"><option value="manual" <?php echo $typeFilter==='manual'?'selected':''; ?>>正式配置</option><option value="auto" <?php echo $typeFilter==='auto'?'selected':''; ?>>自动分配记录</option></select></label>
</div>
<p><button>搜索 / 筛选</button> <a class="btn ghost" href="<?php echo admin_h(cms_admin_url('site_config.php')); ?>">重置</a></p>
</form>

<?php if($typeFilter === 'auto'): ?>
<form method="post" id="site-auto-bulk-delete-form">
<input type="hidden" name="action" value="bulk_delete_auto_domain">
</form>
<form method="post" id="site-auto-clear-form" data-confirm="确定清空当前筛选下的自动分配记录吗？该操作不可恢复。">
<input type="hidden" name="action" value="clear_auto_domain_list">
<input type="hidden" name="clear_q" value="<?php echo admin_h($q); ?>">
<input type="hidden" name="clear_theme" value="<?php echo admin_h($themeFilter); ?>">
</form>
<div class="cc-table-toolbar">
    <div class="cc-batch-actions">
    <button class="btn small danger" type="submit" form="site-auto-bulk-delete-form">批量删除选中</button>
    <button class="btn small danger ghost" type="submit" form="site-auto-clear-form">清空当前列表</button>
    <span>自动分配记录：共 <?php echo intval($autoTotal); ?> 条，第 <?php echo intval($autoPage); ?>/<?php echo intval($autoPages); ?> 页</span>
    </div>
    <form method="get" class="cc-page-size-form">
    <input type="hidden" name="q" value="<?php echo admin_h($q); ?>">
    <input type="hidden" name="theme" value="<?php echo admin_h($themeFilter); ?>">
    <input type="hidden" name="type" value="auto">
    <input type="hidden" name="page" value="1">
    <label>每页
    <select name="page_size" onchange="this.form.submit()">
    <?php foreach(array(20,50,100,200) as $ps): ?><option value="<?php echo $ps; ?>" <?php echo $pageSize===$ps?'selected':''; ?>><?php echo $ps; ?> 条</option><?php endforeach; ?>
    </select>
    </label>
    </form>
</div>
<table>
<tr><th><input type="checkbox" onclick="document.querySelectorAll('.auto-domain-check').forEach(function(x){x.checked=event.target.checked;});"></th><th>序号</th><th>域名</th><th>主题</th><th>资料编号</th><th>名称</th><th>城市</th><th>电话</th><th>备案号</th><th>创建时间</th><th>操作</th></tr>
<?php $i=($autoPage-1)*$autoPageSize+1; foreach($autoPageRows as $domain=>$row): $profile=$row['profile']; ?>
<tr>
<td><input class="auto-domain-check" type="checkbox" form="site-auto-bulk-delete-form" name="domains[]" value="<?php echo admin_h($domain); ?>"></td>
<td><?php echo $i++; ?></td>
<td><?php echo admin_h($domain); ?></td>
<td><?php echo admin_h(($themes[$row['theme']] ?? $row['theme']) . ' / ' . $row['theme']); ?></td>
<td><?php echo admin_h($row['profile_theme'] . ' #' . ($row['profile_index'] + 1)); ?></td>
<td><?php echo admin_h($profile['name'] ?? ''); ?></td>
<td><?php echo admin_h($profile['city'] ?? ''); ?></td>
<td><?php echo admin_h($profile['phone'] ?? ''); ?></td>
<td><?php echo admin_h($profile['icp'] ?? ''); ?></td>
<td><?php echo admin_h($row['cfg']['created_at'] ?? ''); ?></td>
<td class="actions-cell"><div class="row-actions">
<form method="post" data-confirm="确定把该自动记录转为正式配置吗？"><input type="hidden" name="action" value="promote_auto_domain"><input type="hidden" name="domain" value="<?php echo admin_h($domain); ?>"><button class="btn small" type="submit">转正式</button></form>
<form method="post" data-confirm="确定删除该自动分配记录吗？再次访问会重新自动分配。"><input type="hidden" name="action" value="delete_auto_domain"><input type="hidden" name="domain" value="<?php echo admin_h($domain); ?>"><button class="btn small danger" type="submit">删除</button></form>
</div></td>
</tr>
<?php endforeach; ?>
</table>
<?php if(!$autoPageRows): ?><p class="help">暂无匹配的自动分配记录。</p><?php endif; ?>
<div class="pager"><?php if($autoPage>1): ?><a class="btn ghost small" href="<?php echo admin_h(site_config_page_url($autoPage-1)); ?>">上一页</a><?php endif; ?><?php if($autoPage<$autoPages): ?><a class="btn ghost small" href="<?php echo admin_h(site_config_page_url($autoPage+1)); ?>">下一页</a><?php endif; ?></div>

<?php else: ?>
<form method="post" id="site-bulk-delete-form">
<input type="hidden" name="action" value="bulk_delete_domain">
</form>
<form method="post" id="site-clear-form" data-confirm="确定清空当前筛选下的正式域名配置吗？该操作不可恢复。">
<input type="hidden" name="action" value="clear_domain_list">
<input type="hidden" name="clear_q" value="<?php echo admin_h($q); ?>">
<input type="hidden" name="clear_theme" value="<?php echo admin_h($themeFilter); ?>">
</form>
<div class="cc-table-toolbar">
    <div class="cc-batch-actions">
    <button class="btn small danger" type="submit" form="site-bulk-delete-form">批量删除选中</button>
    <button class="btn small danger ghost" type="submit" form="site-clear-form">清空当前列表</button>
    <span>正式配置：共 <?php echo intval($manualTotal); ?> 条，第 <?php echo intval($manualPage); ?>/<?php echo intval($manualPages); ?> 页</span>
    </div>
    <form method="get" class="cc-page-size-form">
    <input type="hidden" name="q" value="<?php echo admin_h($q); ?>">
    <input type="hidden" name="theme" value="<?php echo admin_h($themeFilter); ?>">
    <input type="hidden" name="type" value="manual">
    <input type="hidden" name="page" value="1">
    <label>每页
    <select name="page_size" onchange="this.form.submit()">
    <?php foreach(array(20,50,100,200) as $ps): ?><option value="<?php echo $ps; ?>" <?php echo $pageSize===$ps?'selected':''; ?>><?php echo $ps; ?> 条</option><?php endforeach; ?>
    </select>
    </label>
    </form>
</div>
<table>
<tr><th><input type="checkbox" onclick="document.querySelectorAll('.domain-check').forEach(function(x){x.checked=event.target.checked;});"></th><th>序号</th><th>域名</th><th>company_id</th><th>主题</th><th>企业/学校名称</th><th>城市</th><th>电话</th><th>备案号</th><th>操作</th></tr>
<?php $i=($manualPage-1)*$manualPageSize+1; foreach($manualPageRows as $domain=>$row): $company=$row['company']; ?>
<tr>
<td><input class="domain-check" type="checkbox" form="site-bulk-delete-form" name="domains[]" value="<?php echo admin_h($domain); ?>"></td>
<td><?php echo $i++; ?></td>
<td><?php echo admin_h($domain); ?></td>
<td><?php echo intval($row['cid']); ?></td>
<td><?php echo admin_h(($themes[$row['theme']] ?? $row['theme']) . ' / ' . $row['theme']); ?></td>
<td><?php echo admin_h($company['name'] ?? ''); ?></td>
<td><?php echo admin_h($company['city'] ?? ''); ?></td>
<td><?php echo admin_h($company['phone'] ?? ''); ?></td>
<td><?php echo admin_h($company['icp'] ?? ''); ?></td>
<td class="actions-cell"><div class="row-actions">
<a class="btn small" href="<?php echo admin_h(cms_admin_url('site_config.php')); ?>?edit=<?php echo urlencode($domain); ?>">编辑</a>
<form method="post" data-confirm="确定删除该域名配置吗？"><input type="hidden" name="action" value="delete_domain"><input type="hidden" name="domain" value="<?php echo admin_h($domain); ?>"><button class="btn small danger" type="submit">删除</button></form>
</div></td>
</tr>
<?php endforeach; ?>
</table>
<?php if(!$manualPageRows): ?><p class="help">暂无匹配的正式域名配置。</p><?php endif; ?>
<div class="pager"><?php if($manualPage>1): ?><a class="btn ghost small" href="<?php echo admin_h(site_config_page_url($manualPage-1)); ?>">上一页</a><?php endif; ?><?php if($manualPage<$manualPages): ?><a class="btn ghost small" href="<?php echo admin_h(site_config_page_url($manualPage+1)); ?>">下一页</a><?php endif; ?></div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php admin_footer(); ?>
