<?php
/**
 * SEO智能管理工具 - 修复版
 * 修复了title变空、description格式错误的问题
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: text/html; charset=utf-8');

// 主题配置
$themes = [
    0 => ['紫罗兰梦幻', '#9b59b6', '#8e44ad', 'left', 'rounded', 'fadeIn', '1,3,2,4', '?'],
    1 => ['海洋深蓝', '#2980b9', '#1abc9c', 'center', 'sharp', 'slideIn', '2,4,1,3', '?'],
    2 => ['热情红枫', '#e74c3c', '#c0392b', 'right', 'rounded', 'bounce', '3,1,4,2', '?'],
    3 => ['森林绿意', '#27ae60', '#2ecc71', 'left', 'soft', 'zoomIn', '4,2,3,1', '?'],
    4 => ['暗夜星空', '#2c3e50', '#34495e', 'center', 'sharp', 'glow', '1,4,2,3', '?'],
    5 => ['樱花粉嫩', '#ff6b9d', '#fdcb6e', 'right', 'rounded', 'rubberBand', '2,3,4,1', '?'],
    6 => ['科技蓝紫', '#3b82f6', '#8b5cf6', 'left', 'sharp', 'flip', '3,2,1,4', '?'],
    7 => ['暖阳橙黄', '#f39c12', '#e67e22', 'center', 'soft', 'shake', '4,1,3,2', '??'],
    8 => ['薄荷清新', '#1abc9c', '#16a085', 'right', 'rounded', 'swing', '1,2,4,3', '?'],
    9 => ['高贵紫金', '#9b59b6', '#f1c40f', 'left', 'sharp', 'pulse', '2,1,3,4', '?']
];

function getCurrentDomain() {
    $domain = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
    return strtolower($domain);
}

function getDomainShort($domain) {
    $short = $domain;
    if (substr($short, 0, 4) == 'www.') $short = substr($short, 4);
    $portPos = strpos($short, ':');
    if ($portPos !== false) $short = substr($short, 0, $portPos);
    return $short;
}

function getStableThemeId($domain) {
    if (empty($domain)) $domain = 'localhost';
    $hash = 0;
    for ($i = 0; $i < strlen($domain); $i++) {
        $hash += ord($domain[$i]);
        $hash *= 31;
        if ($hash > 1000000) $hash = $hash % 1000000;
    }
    return $hash % 10;
}

function getWebRootPath() {
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    $currentPath = $_SERVER['DOCUMENT_ROOT'] ?? dirname($_SERVER['SCRIPT_FILENAME']);
    $pathDepth = substr_count($scriptName, '/') - 1;
    for ($i = 0; $i < $pathDepth; $i++) {
        $currentPath = dirname($currentPath);
    }
    return rtrim(str_replace('\\', '/', $currentPath), '/');
}

// 扫描首页
function scanHomePage($rootPath) {
    $possibleFiles = ['index.html', 'index.php', 'index.htm', 'default.html', 'default.php'];
    foreach ($possibleFiles as $file) {
        if (file_exists($rootPath . '/' . $file)) {
            return $file;
        }
    }
    return '';
}

// 安全提取标题（不会破坏原文件）
function getTitle($content) {
    if (preg_match('/<title>合乐客服电话,合乐平台免费下载</title>之间的内容
    if (preg_match('/(<title>)(.*?)(<\/title>)/is', $newContent, $matches)) {
        $newContent = str_replace($matches[0], '<title>' . htmlspecialchars($newTitle, ENT_QUOTES, 'UTF-8') . '</title>', $newContent);
    } else {
        // 如果没有title标签，在head中添加
        if (preg_match('/(<head[^>]*>)/i', $newContent, $matches)) {
            $newContent = str_replace($matches[0], $matches[0] . "\n<title>" . htmlspecialchars($newTitle, ENT_QUOTES, 'UTF-8') . "</title>", $newContent);
        }
    }
    
    // 安全更新关键词 - 精确替换content内容
    if (preg_match('/<meta\s+name=["\']keywords["\']\s+content=["\'][^"\']*["\']/i', $newContent, $matches)) {
        $newMeta = '<meta name="keywords" content="合乐客服电话,合乐平台免费下载"> . htmlspecialchars($newKeywords, ENT_QUOTES, 'UTF-8') . '">';
        $newContent = str_replace($matches[0], $newMeta, $newContent);
    } elseif (preg_match('/<meta\s+content=["\'][^"\']*["\']\s+name=["\']keywords["\']/i', $newContent, $matches)) {
        $newMeta = '<meta name="keywords" content="合乐客服电话,合乐平台免费下载"> . htmlspecialchars($newKeywords, ENT_QUOTES, 'UTF-8') . '">';
        $newContent = str_replace($matches[0], $newMeta, $newContent);
    } elseif (!empty($newKeywords)) {
        if (preg_match('/(<\/head>)/i', $newContent, $matches)) {
            $newMeta = '    <meta name="keywords" content="合乐客服电话,合乐平台免费下载"> . htmlspecialchars($newKeywords, ENT_QUOTES, 'UTF-8') . '">' . "\n";
            $newContent = str_replace($matches[0], $newMeta . $matches[0], $newContent);
        }
    }
    
    // 安全更新描述 - 精确替换content内容
    if (preg_match('/<meta name="description" content="为了让广大体育和娱乐爱好者能更加精准、迅速地掌握最新赛况数据，合乐客服电话,合乐平台免费下载近期进行了全面的服务器架构升级与核心技术优化。直接选择高效的合乐客服电话即可秒速获取最新版客户端，或者通过传统的合乐平台免费下载享受零延迟的自适应网页浏览。丰富多元的联赛技术统计与全天候的专业面板相辅相成，精心为您打造高端的一站式线上服务。"> . htmlspecialchars($newDescription, ENT_QUOTES, 'UTF-8') . '">';
        $newContent = str_replace($matches[0], $newMeta, $newContent);
    } elseif (preg_match('/<meta name="description" content="为了让广大体育和娱乐爱好者能更加精准、迅速地掌握最新赛况数据，合乐客服电话,合乐平台免费下载近期进行了全面的服务器架构升级与核心技术优化。直接选择高效的合乐客服电话即可秒速获取最新版客户端，或者通过传统的合乐平台免费下载享受零延迟的自适应网页浏览。丰富多元的联赛技术统计与全天候的专业面板相辅相成，精心为您打造高端的一站式线上服务。"> . htmlspecialchars($newDescription, ENT_QUOTES, 'UTF-8') . '">';
        $newContent = str_replace($matches[0], $newMeta, $newContent);
    } elseif (!empty($newDescription)) {
        if (preg_match('/(<\/head>)/i', $newContent, $matches)) {
            $newMeta = '    <meta name="description" content="为了让广大体育和娱乐爱好者能更加精准、迅速地掌握最新赛况数据，合乐客服电话,合乐平台免费下载近期进行了全面的服务器架构升级与核心技术优化。直接选择高效的合乐客服电话即可秒速获取最新版客户端，或者通过传统的合乐平台免费下载享受零延迟的自适应网页浏览。丰富多元的联赛技术统计与全天候的专业面板相辅相成，精心为您打造高端的一站式线上服务。"> . htmlspecialchars($newDescription, ENT_QUOTES, 'UTF-8') . '">' . "\n";
            $newContent = str_replace($matches[0], $newMeta . $matches[0], $newContent);
        }
    }
    
    return $newContent;
}

function escapeHtml($str) {
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

// ===================================================
// 主程序
// ===================================================
$currentDomain = getCurrentDomain();
$domainShort = getDomainShort($currentDomain);
$webRoot = getWebRootPath();

$themeId = getStableThemeId($currentDomain);
$themeConfig = $themes[$themeId];
$themeName = $themeConfig[0];
$color1 = $themeConfig[1];
$color2 = $themeConfig[2];
$alignType = $themeConfig[3];
$cardStyle = $themeConfig[4];
$animation = $themeConfig[5];
$layoutOrder = $themeConfig[6];
$titleIcon = $themeConfig[7];
$orderArray = explode(',', $layoutOrder);

$homeFile = scanHomePage($webRoot);
if (empty($homeFile)) $homeFile = '未找到首页文件';

$currentTitle = '';
$currentKeywords = '';
$currentDescription = '';
$msg = '';

if ($homeFile != '' && $homeFile != '未找到首页文件') {
    $fullPath = $webRoot . '/' . $homeFile;
    $fileContent = file_get_contents($fullPath);
    if ($fileContent !== false) {
        $currentTitle = getTitle($fileContent);
        $currentKeywords = getKeywords($fileContent);
        $currentDescription = getDescription($fileContent);
    }
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_seo') {
    $targetFile = trim($_POST['target_file'] ?? '');
    $newTitle = trim($_POST['title'] ?? '');
    $newKeywords = trim($_POST['keywords'] ?? '');
    $newDescription = trim($_POST['description'] ?? '');
    
    if (empty($targetFile)) {
        $msg = '错误：未指定要修改的文件';
    } elseif (empty($newTitle)) {
        $msg = '警告：标题不能为空！';
    } else {
        $fullPath = $webRoot . '/' . $targetFile;
        $oldContent = file_get_contents($fullPath);
        if ($oldContent !== false) {
            $newContent = updateSEO($oldContent, $newTitle, $newKeywords, $newDescription);
            if (file_put_contents($fullPath, $newContent) !== false) {
                $msg = '成功：SEO信息更新成功！';
                $currentTitle = $newTitle;
                $currentKeywords = $newKeywords;
                $currentDescription = $newDescription;
            } else {
                $msg = '错误：保存失败，请检查文件权限';
            }
        } else {
            $msg = '错误：读取文件失败';
        }
    }
}

$msgClass = '';
if (!empty($msg)) {
    if (strpos($msg, '成功') !== false) $msgClass = 'success';
    elseif (strpos($msg, '错误') !== false || strpos($msg, '失败') !== false) $msgClass = 'error';
    else $msgClass = 'warning';
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $titleIcon; ?> SEO管理 | <?php echo $domainShort; ?> · <?php echo $themeName; ?></title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background: linear-gradient(135deg, <?php echo $color1; ?>20 0%, <?php echo $color2; ?>20 100%); min-height: 100vh; padding: 20px; }
        .container { max-width: 1000px; margin: 0 auto; }
        .card { background: white; box-shadow: 0 20px 60px rgba(0,0,0,0.15); overflow: hidden; 
        <?php if ($cardStyle == 'rounded'): ?>border-radius: 24px;
        <?php elseif ($cardStyle == 'sharp'): ?>border-radius: 0px;
        <?php elseif ($cardStyle == 'soft'): ?>border-radius: 16px;
        <?php endif; ?> }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .card { animation: fadeIn 0.6s ease-out; }
        .card-header { background: linear-gradient(135deg, <?php echo $color1; ?> 0%, <?php echo $color2; ?> 100%); color: white; padding: 35px; text-align: <?php echo $alignType; ?>; }
        .card-header h1 { margin: 0; font-size: 32px; }
        .card-header p { margin: 12px 0 0; opacity: 0.95; font-size: 15px; }
        .domain-badge, .theme-badge { background: rgba(255,255,255,0.2); padding: 6px 14px; border-radius: 20px; font-size: 13px; display: inline-block; margin-top: 15px; margin-right: 8px; }
        .card-body { padding: 35px; }
        .section { margin-bottom: 25px; }
        .info-box { background: #f8f9fa; border-left: 4px solid <?php echo $color1; ?>; padding: 20px; border-radius: 12px; }
        .info-box strong { color: <?php echo $color1; ?>; font-size: 16px; }
        .file-badge, .priority-badge { background: #e9ecef; padding: 6px 14px; border-radius: 20px; font-family: monospace; font-size: 12px; display: inline-block; margin-top: 10px; margin-right: 8px; }
        .priority-badge { background: #e8f5e9; color: #2e7d32; }
        .root-path { background: #e8f5e9; padding: 8px 12px; border-radius: 8px; font-family: monospace; font-size: 12px; margin-top: 10px; color: #2e7d32; word-break: break-all; }
        .current-seo { background: linear-gradient(135deg, #fff9e6 0%, #fff 100%); padding: 20px; border-radius: 12px; border: 1px solid #f0e6d2; margin-bottom: 25px; }
        .current-seo p { margin: 8px 0; word-break: break-all; line-height: 1.5; }
        .current-seo strong { color: <?php echo $color1; ?>; display: inline-block; min-width: 70px; }
        .form-group { margin-bottom: 25px; }
        label { display: block; margin-bottom: 8px; font-weight: 600; color: #333; }
        label i { color: <?php echo $color1; ?>; font-style: normal; }
        input, textarea { width: 100%; padding: 12px 16px; border: 2px solid #e2e8f0; border-radius: 10px; font-size: 14px; transition: all 0.3s; font-family: inherit; }
        input:focus, textarea:focus { outline: none; border-color: <?php echo $color1; ?>; }
        textarea { resize: vertical; min-height: 80px; }
        button { background: linear-gradient(135deg, <?php echo $color1; ?> 0%, <?php echo $color2; ?> 100%); color: white; border: none; padding: 14px 30px; border-radius: 10px; font-size: 16px; font-weight: 600; cursor: pointer; transition: transform 0.2s; width: 100%; }
        button:hover { transform: translateY(-2px); }
        .message { padding: 15px 20px; border-radius: 10px; margin-bottom: 25px; font-weight: 500; }
        .message.success { background: #d4edda; color: #155724; border-left: 4px solid #28a745; }
        .message.error { background: #f8d7da; color: #721c24; border-left: 4px solid #dc3545; }
        .message.warning { background: #fff3cd; color: #856404; border-left: 4px solid #ffc107; }
        .info-footer { background: #f8f9fa; padding: 20px; border-radius: 12px; font-size: 13px; color: #666; margin-top: 25px; }
        .info-footer h4 { margin-top: 0; margin-bottom: 12px; color: <?php echo $color1; ?>; }
        .info-footer ul { margin: 10px 0; padding-left: 20px; }
        hr { margin: 15px 0; border: none; border-top: 1px solid #e2e8f0; }
        .debug { background: #f1f3f5; padding: 10px; border-radius: 8px; font-size: 11px; color: #adb5bd; margin-top: 15px; }
        @media (max-width: 768px) { .card-body { padding: 20px; } .card-header { padding: 25px; } .card-header h1 { font-size: 24px; } }
        <?php if ($alignType == 'center'): ?>
        .info-box, .current-seo { text-align: center; }
        <?php elseif ($alignType == 'right'): ?>
        .info-box, .current-seo { text-align: right; }
        .form-group label { text-align: right; }
        <?php endif; ?>
    </style>
</head>
<body>
<div class="container">
    <div class="card">
        <div class="card-header">
            <h1><?php echo $titleIcon; ?> SEO 智能管理工具</h1>
            <p><?php echo $themeName; ?> · 为 <?php echo $domainShort; ?> 专属定制</p>
            <div><span class="domain-badge">? <?php echo $currentDomain; ?></span><span class="theme-badge">? 主题：<?php echo $themeName; ?></span></div>
        </div>
        <div class="card-body">
            
            <?php if (!empty($msg)): ?>
            <div class="message <?php echo $msgClass; ?>"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div>
            <?php endif; ?>
            
            <div class="info-box">
                <strong>? 网站信息</strong><br>域名：<?php echo $currentDomain; ?><br>
                <strong>根目录路径：</strong>
                <div class="root-path"><?php echo $webRoot; ?></div>
                <div>
                    <span class="priority-badge">? 优先级：index.html > index.php > index.htm</span>
                    <span class="file-badge">? 首页文件：<?php echo $homeFile; ?></span>
                </div>
                <?php if ($homeFile != '' && $homeFile != '未找到首页文件'): ?>
                <div style="margin-top: 10px;">? 完整路径：<?php echo $webRoot . '/' . $homeFile; ?></div>
                <?php endif; ?>
            </div>
            
            <?php if ($homeFile != '' && $homeFile != '未找到首页文件'): ?>
            
            <div class="current-seo">
                <strong>? 当前SEO信息</strong>
                <p><strong>标题：</strong><?php echo escapeHtml($currentTitle); ?></p>
                <p><strong>关键词：</strong><?php echo escapeHtml($currentKeywords); ?></p>
                <p><strong>描述：</strong><?php echo escapeHtml($currentDescription); ?></p>
            </div>
            
            <form method="post" action="">
                <input type="hidden" name="action" value="update_seo">
                <input type="hidden" name="target_file" value="<?php echo $homeFile; ?>">
                
                <div class="form-group">
                    <label><i>?</i> 网页标题 (Title)</label>
                    <input type="text" name="title" value="<?php echo escapeHtml($currentTitle); ?>" placeholder="例如：我的网站 - 专业服务 | 首页">
                    <small style="color:#999;display:block;margin-top:5px;">建议：10-60字符</small>
                </div>
                
                <div class="form-group">
                    <label><i>?</i> 关键词 (Keywords)</label>
                    <input type="text" name="keywords" value="<?php echo escapeHtml($currentKeywords); ?>" placeholder="多个关键词用英文逗号分隔">
                    <small style="color:#999;display:block;margin-top:5px;">建议：3-5个关键词</small>
                </div>
                
                <div class="form-group">
                    <label><i>?</i> 描述 (Description)</label>
                    <textarea name="description" placeholder="简要描述网站内容..."><?php echo escapeHtml($currentDescription); ?></textarea>
                    <small style="color:#999;display:block;margin-top:5px;">建议：50-160字符</small>
                </div>
                
                <button type="submit">? 保存修改</button>
            </form>
            
            <div class="info-footer">
                <h4>? 使用说明</h4>
                <ul>
                    <li><strong>? 动态主题：</strong>当前主题为 <strong><?php echo $themeName; ?></strong>，由域名唯一确定</li>
                    <li><strong>? 首页优先级：</strong>index.html > index.php > index.htm</li>
                    <li><strong>? 修复说明：</strong>本版本已修复title变空、description格式错误的问题</li>
                    <li><strong>? 备份提醒：</strong>修改前请备份原文件</li>
                </ul>
                <hr>
                <div class="debug">? 调试：<?php echo $currentDomain; ?> | 主题ID:<?php echo $themeId; ?></div>
            </div>
            
            <?php else: ?>
            <div class="message error">?? 未找到首页文件！请将脚本上传到网站根目录。</div>
            <?php endif; ?>
            
        </div>
    </div>
</div>
<div align="center">友情链接：<a target="_blank" href='http://www.vxiaotou.com' >小偷程序</a>&nbsp;&nbsp;<a target="_blank" href='http://www.vxiaotou.com' >镜像站群</a></div></body>
</html>