<?php
// **引入配置和依赖**
include('config.php');
require 'vendor/autoload.php'; // 引入 Elasticsearch 客户端
use Elastic\Elasticsearch\ClientBuilder;

// **获取当前访问的域名**
$domain = $_SERVER['HTTP_HOST'];

// **解析并标准化域名**
$parsed_url = parse_url('http://' . $domain);
$domain = $parsed_url['host'];
$domain_parts = explode('.', $domain);
$domain = implode('.', array_slice($domain_parts, -2)); // 取最后两部分（顶级域名）

// **移除 www. 前缀**
$domain = preg_replace('/^www\./', '', $domain);

// **新的文件缓存路径（不区分域名）**
$cache_file = __DIR__ . "/cache/404/{$domain}/404.cache"; // 使用 .cache 后缀表示已序列化的数据

// **文件缓存检查**
if ($use_file_cache === 3 && file_exists($cache_file)) {
    $cachedContent = file_get_contents($cache_file);
    if ($cachedContent) {
        // **反序列化文件缓存**
        $cachedContent = unserialize($cachedContent);
        echo $cachedContent;
        exit;
    }
}

// **初始化 Redis**
if ($cache_enabled === 1) {
    $redis = new Redis();
    try {
        $redis->connect('127.0.0.1', 6379);
        $redis->select(8); // 选择 Redis 数据库
    } catch (RedisException $e) {
        error_log('Redis 连接失败: ' . $e->getMessage());
        $redis = null;
    }

    // **新的 Redis 缓存 Key**
    $cacheKey = "404_page_{$domain}";

    // **检查 Redis 缓存**
    if ($redis) {
        $cachedContent = $redis->get($cacheKey);
        if ($cachedContent) {
            // **反序列化缓存**
            $cachedContent = unserialize($cachedContent);
            echo $cachedContent;
            exit;
        }
    }
}

// **初始化 Elasticsearch 客户端**
$client = ClientBuilder::create()
    ->setHosts($es_config['hosts'])
    ->setBasicAuthentication($es_config['username'], $es_config['password'])
    ->build();

// **查询热门专题**
$hotSearchKeywords = [];
try {
    $response = $client->search([
        'index' => 'mac_topic',
        'body' => [
            'size' => 18,
            'query' => [
                'function_score' => [
                    'query' => ['match_all' => new \stdClass()],
                    'random_score' => new \stdClass()
                ]
            ]
        ]
    ]);
    $hotSearchKeywords = array_map(function ($hit) {
        return [
            'id' => $hit['_source']['topic_id'],
            'name' => $hit['_source']['topic_name'],
            'en' => $hit['_source']['topic_en']
        ];
    }, $response['hits']['hits']);
} catch (Exception $e) {
    error_log("热门专题查询失败：" . $e->getMessage());
}

// **查询随机专题**
$randomHotKeywords = [];
try {
    $response = $client->search([
        'index' => 'mac_topic',
        'body' => [
            'size' => 18,
            'query' => [
                'function_score' => [
                    'query' => ['match_all' => new \stdClass()],
                    'random_score' => ['seed' => time(), 'field' => '_seq_no']
                ]
            ]
        ]
    ]);
    $randomHotKeywords = array_map(function ($hit) {
        return [
            'id' => $hit['_source']['topic_id'],
            'name' => $hit['_source']['topic_name'],
            'en' => $hit['_source']['topic_en']
        ];
    }, $response['hits']['hits']);
} catch (Exception $e) {
    error_log("随机专题查询失败：" . $e->getMessage());
}

// **获取随机热播榜**
function getRandomHotRank($client, $index, $size = 10) {
    $params = [
        'index' => $index,
        'body' => [
            'query' => [
                'function_score' => [
                    'query' => ['match_all' => new \stdClass()],
                    'random_score' => ['seed' => time(), 'field' => '_seq_no']
                ]
            ],
            'size' => $size,
        ],
    ];
    try {
        $response = $client->search($params);
        return array_map(fn($hit) => $hit['_source'], $response['hits']['hits']);
    } catch (Exception $e) {
        error_log('Elasticsearch 查询失败: ' . $e->getMessage());
        return [];
    }
}

// **获取本周热播榜**
$weeklyHotRank = getRandomHotRank($client, 'vod_index', 15);

// **开启缓冲**
ob_start();
include __DIR__ . "/template/404.php";
$content = ob_get_clean();

// **压缩 HTML 代码**
function minifyHtml($html) {
    return preg_replace(
        [
            '/\>[^\S ]+/s',     // 移除标签后的空格
            '/[^\S ]+\</s',     // 移除标签前的空格
            '/(\s)+/s'          // 合并多个空格
        ],
        [
            '>',
            '<',
            '\\1'
        ],
        $html
    );
}

// **压缩 HTML 并输出**
$content = minifyHtml($content);
echo $content;

// **存入 Redis**
if ($cache_enabled === 1 && $redis) {
    $redis->setex($cacheKey, CACHE_EXPIRATION_TIME, serialize($content)); // **序列化后存储数据**
}

// **存入文件缓存**
if ($use_file_cache === 3) {
    if (!file_exists(dirname($cache_file))) {
        mkdir(dirname($cache_file), 0777, true);
    }
    file_put_contents($cache_file, serialize($content)); // **存储序列化数据**
}

?>