<?php
// 引入后台路径
require_once $_SERVER['DOCUMENT_ROOT'] . '/data1/admin.php';
/*
 * Name: 泛程序系统
 * 禁止用于违法、违规行业，仅供本地学习参考使用，禁止联网采集！
 */
header("Content-type: text/html; charset=utf-8");

// session配置
@ini_set('memory_limit',         '1024M');// 将内存限制增加到 1024MB，可根据实际情况调整
@ini_set('session.cache_expire',  180);
@ini_set('session.use_trans_sid', 0);
@ini_set('session.use_cookies',   1);
@ini_set('session.auto_start',    0);

// 引入配置文件
require_once 'config.php';
include  $tj.'/t.php';
include  'fangke.php';
require_once 'waf.php';
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$fullPageCacheDir = $_SERVER['DOCUMENT_ROOT'] . '/cache1';
$fullPageCachePath = $fullPageCacheDir . '/' . md5($currentUrl) . '.page.html';

// Read the fully rendered page cache before any template selection or random replacement.
if ($opencache == 1 && is_file($fullPageCachePath)) {
    readfile($fullPageCachePath);
    exit;
}

$mubanDir = $google == 1 ? 'ggtemplates1' : 'templates1';

if ($indexnow == 1) {
require_once 'indexnow.php';
} 

$dataDir = 'data1';

function collectThemeDirs($baseDir, $selectedThemes = []) {
    $themeDirs = [];

    if (!empty($selectedThemes)) {
        foreach ($selectedThemes as $themeName) {
            $dir = $baseDir . '/' . $themeName;
            if (file_exists($dir . '/index.html') && file_exists($dir . '/show.html')) {
                $themeDirs[] = $dir;
            }
        }
        return $themeDirs;
    }

    $dirs = glob($baseDir . '/*', GLOB_ONLYDIR);
    if ($dirs) {
        foreach ($dirs as $dir) {
            if (basename($dir) === '备份') continue;
            if (file_exists($dir . '/index.html') && file_exists($dir . '/show.html')) {
                $themeDirs[] = $dir;
            }
        }
    }

    return $themeDirs;
}

// 根据后台实际勾选结果生成可调用的模板池
$themeDirs = [];
$configFile = $_SERVER['DOCUMENT_ROOT'] . '/data1/theme_config.json';
$config = [];

if (file_exists($configFile)) {
    $config = json_decode(file_get_contents($configFile), true);
    if (!is_array($config)) {
        $config = [];
    }
}

$selectedTemplates = isset($config['templates1']) && is_array($config['templates1']) ? $config['templates1'] : [];
$selectedGgtemplates = isset($config['ggtemplates1']) && is_array($config['ggtemplates1']) ? $config['ggtemplates1'] : [];

if ($google == 1) {
    // 开启“使用谷歌模板”后，强制使用国际模板 theme1
    $mubanDir = 'ggtemplates1';
    $forcedTheme = 'ggtemplates1/theme1';
    if (file_exists($forcedTheme . '/index.html') && file_exists($forcedTheme . '/show.html')) {
        $themeDirs = [$forcedTheme];
    } else {
        $themeDirs = collectThemeDirs('ggtemplates1', ['theme1']);
    }
} elseif (!empty($selectedTemplates) && !empty($selectedGgtemplates)) {
    // 国内模板和国际模板都勾选时，两边合并后统一随机调用
    $themeDirs = array_merge(
        collectThemeDirs('templates1', $selectedTemplates),
        collectThemeDirs('ggtemplates1', $selectedGgtemplates)
    );
} elseif (!empty($selectedTemplates)) {
    $mubanDir = 'templates1';
    $themeDirs = collectThemeDirs('templates1', $selectedTemplates);
} elseif (!empty($selectedGgtemplates)) {
    $mubanDir = 'ggtemplates1';
    $themeDirs = collectThemeDirs('ggtemplates1', $selectedGgtemplates);
} else {
    // 如果后台没有勾选任何模板，则兼容原有单分类逻辑
    if (isset($config['active_category']) && in_array($config['active_category'], ['templates1', 'ggtemplates1'], true)) {
        $mubanDir = $config['active_category'];
    }
    $themeDirs = collectThemeDirs($mubanDir);
}

if (!empty($themeDirs)) {
    // 随机选择一套模板
    $theme = $themeDirs[array_rand($themeDirs)];
    
    if ($uri === '/' || preg_match('#^/(index\.(php|html|htm|asp))$#i', $uri)) {
        $templatePath = $theme . '/index.html';
    } elseif (preg_match('#\.[^/]+$#', $uri)) {
        $templatePath = $theme . '/show.html';
    } elseif (preg_match('#/$#', $uri) || !strpos(basename($uri), '.')) {
        $templatePath = $theme . '/list.html';
    } else {
        $templatePath = $theme . '/index.html';
    }
} else {
    // 兼容旧的单一模板结构 (index/ list/ show/ 目录)
    if ($uri === '/' || preg_match('#^/(index\.(php|html|htm|asp))$#i', $uri)) {
        $templatePath = $mubanDir.'/index';
    //下面代码可以指定一些你想要的后缀作为内页
    } elseif (preg_match('#\.[^/]+$#', $uri)) {  //} elseif (preg_match('#\.(html|shtml|php|ppt|doc|txt|htm)$#i', $uri)) {
        $templatePath = $mubanDir.'/show';
    } elseif (preg_match('#/$#', $uri) || !strpos(basename($uri), '.')) {
        $templatePath = $mubanDir.'/list';
    } else {
        $templatePath = $mubanDir.'/index';
    }
}

$muban = process($templatePath, $dataDir);

if ($no == 1) {
    $noTemplatePath = 'templates1/no.html';
    if (file_exists($noTemplatePath)) {
        $noTemplateContent = file_get_contents($noTemplatePath);
        $muban = $noTemplateContent . $muban;
    } else {
        $muban = '不存在防查看' . $muban;
    }
}


if ($onlinks == 1) {
    // 打开 links.php 文件并读取其内容
    ob_start(); // 开启输出缓冲
    include 'links.php';
    $linksContent = ob_get_clean(); // 获取并清空输出缓冲区的内容

    // 将 links.php 的内容添加到 $muban 后面
    $muban = $muban . $linksContent;
}

if ($opencache == 1) {
    if (!is_dir($fullPageCacheDir)) {
        mkdir($fullPageCacheDir, 0777, true);
    }
    file_put_contents($fullPageCachePath, $muban, LOCK_EX);
}

// 输出最终的 $muban
echo $muban;
?>
