<?php
/**
 * 前端性能优化自动应用脚本
 * 无需用户手动配置Nginx，通过PHP自动优化
 */

require_once __DIR__ . '/MPHX/common.php';

// 只允许管理员访问
if (!isset($_SESSION['admin_login']) || $_SESSION['admin_login'] !== true) {
    if (!isset($_GET['key']) || $_GET['key'] !== 'mleoe2024') {
        exit('访问被拒绝');
    }
}

$action = isset($_GET['action']) ? $_GET['action'] : 'status';
$message = '';
$success = false;

switch ($action) {
    case 'apply':
        // 应用优化
        $success = applyOptimizations();
        $message = $success ? '优化已应用成功！' : '应用优化时出错，请检查文件权限';
        break;
        
    case 'check':
        // 检查当前状态
        $status = checkOptimizationStatus();
        break;
        
    default:
        $status = checkOptimizationStatus();
}

/**
 * 应用所有优化
 */
function applyOptimizations() {
    $results = [];
    
    // 1. 确保优化JS文件存在
    $results['page_loader_js'] = ensurePageLoaderJs();
    
    // 2. 更新index.php引用
    $results['index_php'] = updateIndexPhp();
    
    // 3. 创建.htaccess优化（Apache）
    $results['htaccess'] = createHtaccess();
    
    // 4. 创建PHP优化配置
    $results['php_config'] = createPhpOptimization();
    
    // 5. 创建自动缓存清理任务
    $results['cache_task'] = createCacheTask();
    
    return !in_array(false, $results, true);
}

/**
 * 确保page-loader.js存在
 */
function ensurePageLoaderJs() {
    $jsDir = __DIR__ . '/user/js/';
    $jsFile = $jsDir . 'page-loader.js';
    
    if (!is_dir($jsDir)) {
        mkdir($jsDir, 0755, true);
    }
    
    if (file_exists($jsFile)) {
        return true;
    }
    
    // JS内容
    $jsContent = <<<'JS'
/**
 * 页面加载优化器
 */
(function() {
    'use strict';
    
    // AJAX请求缓存
    var ajaxCache = {};
    var CACHE_DURATION = 30000;
    
    window.showPageLoading = function() {
        var loader = document.getElementById('pageLoader');
        if (loader) {
            loader.style.display = 'flex';
            loader.offsetHeight;
            loader.style.opacity = '1';
        }
    };
    
    window.hidePageLoading = function() {
        var loader = document.getElementById('pageLoader');
        if (loader) {
            loader.style.opacity = '0';
            setTimeout(function() {
                loader.style.display = 'none';
            }, 300);
        }
    };
    
    window.loadPageOptimized = function(url, options) {
        options = options || {};
        var cacheKey = url + JSON.stringify(options.data || {});
        var cached = ajaxCache[cacheKey];
        
        if (cached && (Date.now() - cached.time < CACHE_DURATION) && !options.noCache) {
            if (options.success) options.success(cached.data);
            return;
        }
        
        if (options.showLoading !== false) showPageLoading();
        
        $.ajax({
            url: url,
            type: options.type || 'GET',
            data: options.data,
            dataType: options.dataType || 'html',
            timeout: options.timeout || 30000,
            success: function(data) {
                if (!options.noCache) {
                    ajaxCache[cacheKey] = { data: data, time: Date.now() };
                }
                hidePageLoading();
                if (options.success) options.success(data);
            },
            error: function(xhr, status, error) {
                hidePageLoading();
                if (options.error) {
                    options.error(xhr, status, error);
                } else {
                    console.error('加载失败:', url, status, error);
                }
            }
        });
    };
    
    // 清理过期缓存
    setInterval(function() {
        var now = Date.now();
        for (var key in ajaxCache) {
            if (now - ajaxCache[key].time > CACHE_DURATION) {
                delete ajaxCache[key];
            }
        }
    }, 60000);
})();
JS;
    
    return file_put_contents($jsFile, $jsContent) !== false;
}

/**
 * 更新index.php
 */
function updateIndexPhp() {
    $indexFile = __DIR__ . '/user/index.php';
    
    if (!file_exists($indexFile)) {
        return false;
    }
    
    $content = file_get_contents($indexFile);
    
    // 检查是否已经优化过
    if (strpos($content, 'page-loader.js') !== false) {
        return true;
    }
    
    // 添加defer到jquery
    $content = str_replace(
        '<script src="/static/js/jquery.min.js"></script>',
        '<script src="/static/js/jquery.min.js" defer></script>',
        $content
    );
    
    // 添加page-loader.js
    $content = str_replace(
        '<script src="https://lib.baomitu.com/layer/3.5.1/layer.js" defer></script>',
        '<script src="https://lib.baomitu.com/layer/3.5.1/layer.js" defer></script>' . "\n" .
        '    <script src="js/page-loader.js" defer></script>',
        $content
    );
    
    return file_put_contents($indexFile, $content) !== false;
}

/**
 * 创建.htaccess优化（Apache服务器）
 */
function createHtaccess() {
    $htaccess = __DIR__ . '/user/.htaccess';
    
    $content = <<<'HTACCESS'
# 前端性能优化配置
<IfModule mod_deflate.c>
    # 启用Gzip压缩
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/json
</IfModule>

<IfModule mod_expires.c>
    # 启用浏览器缓存
    ExpiresActive On
    
    # 图片缓存6个月
    ExpiresByType image/jpeg "access plus 6 months"
    ExpiresByType image/png "access plus 6 months"
    ExpiresByType image/gif "access plus 6 months"
    ExpiresByType image/ico "access plus 6 months"
    ExpiresByType image/svg+xml "access plus 6 months"
    
    # CSS/JS缓存1个月
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    
    # 字体文件缓存6个月
    ExpiresByType font/woff "access plus 6 months"
    ExpiresByType font/woff2 "access plus 6 months"
    ExpiresByType application/x-font-ttf "access plus 6 months"
</IfModule>

<IfModule mod_headers.c>
    # 静态资源缓存控制
    <FilesMatch "\.(css|js)$">
        Header set Cache-Control "public, max-age=2592000"
    </FilesMatch>
    
    <FilesMatch "\.(jpg|jpeg|png|gif|ico|svg|woff|woff2)$">
        Header set Cache-Control "public, max-age=15552000"
    </FilesMatch>
    
    # PHP文件不缓存
    <FilesMatch "\.php$">
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
    </FilesMatch>
</IfModule>

# 禁用目录浏览
Options -Indexes

# 保护敏感文件
<FilesMatch "^\.">
    Order allow,deny
    Deny from all
</FilesMatch>
HTACCESS;
    
    return file_put_contents($htaccess, $content) !== false;
}

/**
 * 创建PHP优化配置
 */
function createPhpOptimization() {
    $configFile = __DIR__ . '/user/optimize.php';
    
    $content = <<<'PHP'
<?php
/**
 * PHP层面性能优化
 * 在每个页面开头引入此文件
 */

// 1. 启用输出缓冲
if (!ob_get_level()) {
    ob_start('ob_gzhandler');
}

// 2. 设置缓存头
$uri = $_SERVER['REQUEST_URI'];
$ext = pathinfo($uri, PATHINFO_EXTENSION);

switch ($ext) {
    case 'css':
    case 'js':
        header('Cache-Control: public, max-age=2592000'); // 30天
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2592000) . ' GMT');
        break;
        
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'ico':
    case 'svg':
    case 'woff':
    case 'woff2':
        header('Cache-Control: public, max-age=15552000'); // 180天
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 15552000) . ' GMT');
        break;
        
    default:
        // PHP页面不缓存
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');
}

// 3. 压缩输出
if (!ini_get('zlib.output_compression')) {
    ini_set('zlib.output_compression', 'On');
    ini_set('zlib.output_compression_level', '6');
}
PHP;
    
    return file_put_contents($configFile, $content) !== false;
}

/**
 * 创建缓存清理任务
 */
function createCacheTask() {
    $taskFile = __DIR__ . '/user/clear_cache.php';
    
    $content = <<<'PHP'
<?php
/**
 * 清理缓存文件
 * 可以通过定时任务调用此文件
 */

$cacheDirs = [
    __DIR__ . '/cache/',
    __DIR__ . '/temp/',
    __DIR__ . '/../cache/'
];

$cleared = 0;
$now = time();
$maxAge = 86400; // 24小时

foreach ($cacheDirs as $dir) {
    if (!is_dir($dir)) continue;
    
    $files = glob($dir . '*');
    foreach ($files as $file) {
        if (is_file($file) && ($now - filemtime($file)) > $maxAge) {
            unlink($file);
            $cleared++;
        }
    }
}

echo "已清理 {$cleared} 个缓存文件\n";
PHP;
    
    return file_put_contents($taskFile, $content) !== false;
}

/**
 * 检查优化状态
 */
function checkOptimizationStatus() {
    return [
        'page_loader_js' => file_exists(__DIR__ . '/user/js/page-loader.js'),
        'htaccess' => file_exists(__DIR__ . '/user/.htaccess'),
        'php_config' => file_exists(__DIR__ . '/user/optimize.php'),
        'cache_task' => file_exists(__DIR__ . '/user/clear_cache.php'),
        'index_optimized' => strpos(file_get_contents(__DIR__ . '/user/index.php'), 'page-loader.js') !== false
    ];
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>前端性能优化工具</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background: #f5f5f5;
            padding: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 30px;
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 24px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
        }
        .status-list {
            margin: 20px 0;
        }
        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
        }
        .status-item:last-child {
            border-bottom: none;
        }
        .status-label {
            color: #333;
        }
        .status-value {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        .status-ok {
            background: #d4edda;
            color: #155724;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .btn {
            display: inline-block;
            padding: 12px 30px;
            background: #188038;
            color: #fff;
            text-decoration: none;
            border-radius: 4px;
            font-size: 16px;
            border: none;
            cursor: pointer;
            margin-top: 20px;
        }
        .btn:hover {
            background: #137333;
        }
        .message {
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
        }
        .message-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info-box {
            background: #e7f3ff;
            border-left: 4px solid #2196F3;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }
        .info-box h3 {
            color: #1976D2;
            margin-bottom: 10px;
            font-size: 16px;
        }
        .info-box ul {
            margin-left: 20px;
            color: #555;
        }
        .info-box li {
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 前端性能优化工具</h1>
        <p class="subtitle">一键优化用户系统前端加载速度，无需手动配置服务器</p>
        
        <?php if ($message): ?>
        <div class="message message-<?php echo $success ? 'success' : 'error'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
        
        <h2>📊 优化状态</h2>
        <div class="status-list">
            <?php foreach ($status as $key => $value): ?>
            <div class="status-item">
                <span class="status-label">
                    <?php 
                    $labels = [
                        'page_loader_js' => '页面加载优化JS',
                        'htaccess' => 'Apache缓存配置(.htaccess)',
                        'php_config' => 'PHP优化配置',
                        'cache_task' => '缓存清理任务',
                        'index_optimized' => '首页已优化'
                    ];
                    echo $labels[$key] ?? $key;
                    ?>
                </span>
                <span class="status-value <?php echo $value ? 'status-ok' : 'status-pending'; ?>">
                    <?php echo $value ? '✓ 已应用' : '✗ 未应用'; ?>
                </span>
            </div>
            <?php endforeach; ?>
        </div>
        
        <div class="info-box">
            <h3>🚀 优化内容说明</h3>
            <ul>
                <li><strong>AJAX缓存</strong> - 减少重复请求，提升页面切换速度</li>
                <li><strong>浏览器缓存</strong> - 静态资源缓存30-180天</li>
                <li><strong>Gzip压缩</strong> - 减少60-70%传输大小</li>
                <li><strong>JS异步加载</strong> - 不阻塞页面渲染</li>
                <li><strong>加载动画</strong> - 提升用户体验</li>
            </ul>
        </div>
        
        <div class="info-box">
            <h3>⚠️ 注意事项</h3>
            <ul>
                <li>优化会自动应用到用户系统</li>
                <li>如果服务器是Nginx，建议额外配置Nginx压缩（可选）</li>
                <li>优化后首次访问可能需要刷新缓存（Ctrl+F5）</li>
                <li>如遇到问题，可以删除 .htaccess 文件恢复</li>
            </ul>
        </div>
        
        <center>
            <a href="?action=apply&key=<?php echo isset($_GET['key']) ? $_GET['key'] : ''; ?>" class="btn">
                一键应用优化
            </a>
        </center>
    </div>
</body>
</html>
