<?php
/**
* 模板渲染函数 - 优化缓存版本
*/
function render_index($page = 1) {
    $api = $GLOBALS['zblog_api'];
    $smarty = init_smarty();

    // 获取显示设置
    $display_config = $GLOBALS['config']['display'] ?? [];
    $index_posts_count = $display_config['index_posts_count'] ?? 10;

    // 使用智能缓存
    $cache_key = "index_page_{$page}_{$index_posts_count}";

    $data = smart_cache($cache_key, function() use ($api, $page, $index_posts_count) {
        // 获取公用数据
        $common_data = get_common_data();

        // 获取文章列表 - 应用显示数量设置
        $lists_result = $api->lists($page, $index_posts_count);

        if ($lists_result['code'] != 200) {
            if ($lists_result['code'] == 404) {
                $lists_result['data'] = [];
                $lists_result['pagination'] = [
                    'page' => $page,
                    'perpage' => $index_posts_count,
                    'total' => 0,
                    'total_pages' => 0,
                    'has_next' => false,
                    'has_prev' => false
                ];
            } else {
                display_error($lists_result['code'], $lists_result['message']);
            }
        }

        // 获取所有分类用于导航
        $all_categories = get_all_categories();

        $data = array_merge($common_data, [
            'page_title' => $GLOBALS['config']['site']['name'] ?? '网站',
            'posts' => process_posts_for_template($lists_result['data'] ?? []),
            'pagination' => $lists_result['pagination'] ?? [],
            'categories' => $all_categories,
            'current_page' => $page,
            'mod' => 'index',
            'config' => $GLOBALS['config'],
            'csrf_token' => generate_csrf_token(),
            'base_url' => $GLOBALS['base_url']
        ]);

        // 获取自定义数据
        $custom_data = get_custom_data('index');
        $data = array_merge($data, $custom_data);

        preprocess_pagination($data['pagination']);
        return $data;
    }, $GLOBALS['config']['cache']['list_time'] ?? 600);

    $smarty->assign($data);
    $smarty->display('index.tpl');
}

function render_category($cate_id, $page = 1) {
    $api = $GLOBALS['zblog_api'];
    $smarty = init_smarty();

    // 获取显示设置
    $display_config = $GLOBALS['config']['display'] ?? [];
    $category_posts_count = $display_config['category_posts_count'] ?? 10;

    $cache_key = "category_{$cate_id}_{$page}_{$category_posts_count}";
    
    // 安全获取缓存时间
    $cache_config = $GLOBALS['config']['cache'] ?? [];
    $cache_time = $cache_config['list_time'] ?? 600;
    
    $cached_data = $GLOBALS['cache']->get($cache_key, $cache_time);

    if ($cached_data !== null) {
        $smarty->assign($cached_data);
        $smarty->display('category.tpl');
        return;
    }

    // 获取公用数据
    $common_data = get_common_data();

    // 获取分类文章列表 - 应用显示数量设置
    $lists_result = $api->lists($page, $category_posts_count, $cate_id);

    if ($lists_result['code'] != 200) {
        if ($lists_result['code'] == 404) {
            $lists_result['data'] = [];
            $lists_result['pagination'] = [
                'page' => $page,
                'perpage' => $category_posts_count,
                'total' => 0,
                'total_pages' => 0,
                'has_next' => false,
                'has_prev' => false
            ];
        } else {
            display_error($lists_result['code'], $lists_result['message']);
        }
    }

    // 获取当前分类信息
    $current_category = null;
    foreach ($common_data['all_categories'] as $category) {
        if ($category['id'] == $cate_id) {
            $current_category = $category;
            break;
        }
    }

    if (!$current_category) {
        display_error(404, '分类不存在');
    }

    // 获取所有分类用于导航
    $all_categories = get_all_categories();

    $data = array_merge($common_data, [
        'page_title' => $current_category['name'],
        'posts' => process_posts_for_template($lists_result['data'] ?? []),
        'pagination' => $lists_result['pagination'] ?? [],
        'categories' => $all_categories,
        'current_category' => $current_category,
        'current_page' => $page,
        'mod' => 'category',
        'config' => $GLOBALS['config'],
        'csrf_token' => generate_csrf_token(),
        'base_url' => $GLOBALS['base_url']
    ]);

    // 获取自定义数据
    $custom_data = get_custom_data('category');
    $data = array_merge($data, $custom_data);

    preprocess_pagination($data['pagination']);

    $smarty->assign($data);
    $smarty->display('category.tpl');

    $GLOBALS['cache']->set($cache_key, $data);
}

function render_post($post_id) {
    $api = $GLOBALS['zblog_api'];
    $smarty = init_smarty();

    // 获取公用数据
    $common_data = get_common_data();

    // 获取文章详情
    $post_result = $api->get_post($post_id);

    if ($post_result['code'] != 200) {
        display_error($post_result['code'], $post_result['message']);
    }

    $post_data = $post_result['data'];

    // 修复：文章内容解析HTML标签
    $post_data['content'] = htmlspecialchars_decode($post_data['content']);

    // 处理文章数据
    if (!empty($post_data['tags'])) {
        $post_data['tags_array'] = array_filter(array_map('trim', explode(',', $post_data['tags'])));
    } else {
        $post_data['tags_array'] = [];
    }

    if (isset($post_data['create_time'])) {
        $post_data['create_time_formatted'] = date('Y-m-d H:i', $post_data['create_time']);
        if (isset($post_data['update_time']) && $post_data['update_time'] != $post_data['create_time']) {
            $post_data['update_time_formatted'] = date('Y-m-d H:i', $post_data['update_time']);
        }
    }

    // 获取所有分类用于导航
    $all_categories = get_all_categories();

    $data = array_merge($common_data, [
        'page_title' => $post_data['title'] ?? '文章详情',
        'post' => $post_data,
        'categories' => $all_categories,
        'mod' => 'post',
        'config' => $GLOBALS['config'],
        'csrf_token' => generate_csrf_token(),
        'base_url' => $GLOBALS['base_url']
    ]);

    // 获取自定义数据
    $custom_data = get_custom_data('post');
    $data = array_merge($data, $custom_data);

    $smarty->assign($data);
    $smarty->display('post.tpl');
}

function render_author($author_id, $page = 1) {
    $api = $GLOBALS['zblog_api'];
    $smarty = init_smarty();

    // 获取显示设置
    $display_config = $GLOBALS['config']['display'] ?? [];
    $author_posts_count = $display_config['category_posts_count'] ?? 10; // 使用分类页设置

    $cache_key = "author_{$author_id}_{$page}_{$author_posts_count}";
    
    // 安全获取缓存时间
    $cache_config = $GLOBALS['config']['cache'] ?? [];
    $cache_time = $cache_config['list_time'] ?? 600;
    
    $cached_data = $GLOBALS['cache']->get($cache_key, $cache_time);

    if ($cached_data !== null) {
        $smarty->assign($cached_data);
        $smarty->display('author.tpl');
        return;
    }

    // 获取公用数据
    $common_data = get_common_data();

    $author_result = $api->authorlists($author_id, $page, $author_posts_count);

    if ($author_result['code'] != 200) {
        if ($author_result['code'] == 404) {
            $author_result['data'] = [];
            $author_result['pagination'] = [
                'page' => $page,
                'perpage' => $author_posts_count,
                'total' => 0,
                'total_pages' => 0,
                'has_next' => false,
                'has_prev' => false
            ];
        } else {
            display_error($author_result['code'], $author_result['message']);
        }
    }

    $author_name = '';
    if (!empty($author_result['data'][0]['author'])) {
        $author_name = $author_result['data'][0]['author'];
    }

    // 获取所有分类用于导航
    $all_categories = get_all_categories();

    $data = array_merge($common_data, [
        'page_title' => $author_name ? $author_name . '的文章' : '作者文章',
        'posts' => process_posts_for_template($author_result['data'] ?? []),
        'pagination' => $author_result['pagination'] ?? [],
        'categories' => $all_categories,
        'author_name' => $author_name,
        'author_id' => $author_id,
        'current_page' => $page,
        'mod' => 'author',
        'config' => $GLOBALS['config'],
        'csrf_token' => generate_csrf_token(),
        'base_url' => $GLOBALS['base_url']
    ]);

    // 获取自定义数据
    $custom_data = get_custom_data('author');
    $data = array_merge($data, $custom_data);

    preprocess_pagination($data['pagination']);

    $smarty->assign($data);
    $smarty->display('author.tpl');

    $GLOBALS['cache']->set($cache_key, $data);
}

function render_search($keyword, $page = 1) {
    $api = $GLOBALS['zblog_api'];
    $smarty = init_smarty();

    // 获取显示设置
    $display_config = $GLOBALS['config']['display'] ?? [];
    $search_posts_count = $display_config['category_posts_count'] ?? 10; // 使用分类页设置

    $cache_key = "search_" . md5("{$keyword}_{$page}_{$search_posts_count}");
    
    // 安全获取缓存时间
    $cache_config = $GLOBALS['config']['cache'] ?? [];
    $cache_time = $cache_config['list_time'] ?? 600;
    
    $cached_data = $GLOBALS['cache']->get($cache_key, $cache_time);

    if ($cached_data !== null) {
        $smarty->assign($cached_data);
        $smarty->display('search.tpl');
        return;
    }

    // 获取公用数据
    $common_data = get_common_data();

    $search_result = $api->search($keyword, $page, $search_posts_count);

    if ($search_result['code'] != 200) {
        if ($search_result['code'] == 404) {
            $search_result['data'] = [];
            $search_result['pagination'] = [
                'page' => $page,
                'perpage' => $search_posts_count,
                'total' => 0,
                'total_pages' => 0,
                'has_next' => false,
                'has_prev' => false
            ];
        } else {
            display_error($search_result['code'], $search_result['message']);
        }
    }

    // 获取所有分类用于导航
    $all_categories = get_all_categories();

    $data = array_merge($common_data, [
        'page_title' => '搜索: ' . $keyword,
        'posts' => process_posts_for_template($search_result['data'] ?? []),
        'pagination' => $search_result['pagination'] ?? [],
        'categories' => $all_categories,
        'keyword' => $keyword,
        'current_page' => $page,
        'mod' => 'search',
        'config' => $GLOBALS['config'],
        'csrf_token' => generate_csrf_token(),
        'base_url' => $GLOBALS['base_url']
    ]);

    // 获取自定义数据
    $custom_data = get_custom_data('search');
    $data = array_merge($data, $custom_data);

    preprocess_pagination($data['pagination']);

    $smarty->assign($data);
    $smarty->display('search.tpl');

    $GLOBALS['cache']->set($cache_key, $data);
}

/**
* 渲染缓存更新页面
*/
function render_update_cache() {
    if (!is_allowed_ip()) {
        display_error(403, '禁止访问');
    }

    $api = $GLOBALS['zblog_api'];
    $result = $api->refresh_all_cache();

    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}
?>