<?php
/**
* 高性能API客户端类 - 修复缓存问题和PHP版本兼容性
*/

// 安全检查
if (!defined('INCLUDE_PATH')) {
    die('禁止直接访问');
}

class ZBlogAPI {
    private $fetcher;
    private $config;
    private $cache;

    public function __construct() {
        require_once INCLUDE_PATH . '/base.php';
        require_once INCLUDE_PATH . '/cache.php'; // 确保包含cache.php

        $this->fetcher = new RemoteDataFetcher();
        
        // 安全地获取配置
        $this->config = $GLOBALS['config']['api'] ?? [];

        // 安全地初始化缓存对象
        if (isset($GLOBALS['cache']) && is_object($GLOBALS['cache'])) {
            $this->cache = $GLOBALS['cache'];
        } else {
            // 如果全局缓存不存在，创建新的缓存实例
            $this->cache = new Cache();
            $GLOBALS['cache'] = $this->cache;
        }

        $this->fetcher->setHeaders([
            'Accept: application/json',
            'Cache-Control: no-cache',
            'Connection: close'
        ]);
    }

    /**
    * 生成签名URL - PHP 5.6+ 兼容版本
    */
    private function build_url($params = []) {
        $base_url = rtrim($this->config['apiurl'] ?? '', '/') . '/index.php?wensha_api=index';

        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $randomStr = substr(str_shuffle($chars), 0, 4);

        $sign_string = ($this->config['skid'] ?? '') . ($this->config['skey'] ?? '') . ($this->config['skid'] ?? '') . $randomStr;

        switch ($this->config['stype'] ?? 'md5') {
            case 'md5':
                $sign = md5($sign_string);
                break;
            case 'sha1':
                $sign = sha1($sign_string);
                break;
            case 'sha256':
                $sign = hash('sha256', $sign_string);
                break;
            default:
                $sign = md5($sign_string);
        }

        $url = $base_url . '&skid=' . ($this->config['skid'] ?? '') . '&random=' . $randomStr . '&sign=' . $sign;

        foreach ($params as $key => $value) {
            $url .= '&' . $key . '=' . urlencode($value);
        }

        return $url;
    }

    /**
    * 发送API请求 - 增强错误处理
    */
    private function request($url) {
        $result = $this->fetcher->get($url);

        if ($result === false) {
            $error = $this->fetcher->getLastError();
            return [
                'code' => $error['code'] ?: 500,
                'message' => 'API请求失败: ' . $error['message']
            ];
        }

        $data = json_decode($result, true);
        if (!$data || !isset($data['code'])) {
            return [
                'code' => 500,
                'message' => 'API响应格式错误'
            ];
        }

        return $data;
    }

    /**
    * 安全的缓存获取方法
    */
    private function safe_cache_get($cache_key, $cache_time = 600) {
        if (!$this->cache || !method_exists($this->cache, 'get')) {
            return null;
        }
        return $this->cache->get($cache_key, $cache_time);
    }

    /**
    * 安全的缓存设置方法
    */
    private function safe_cache_set($cache_key, $data) {
        if (!$this->cache || !method_exists($this->cache, 'set')) {
            return false;
        }
        return $this->cache->set($cache_key, $data);
    }

    /**
    * 获取文章列表
    */
    public function lists($page = 1, $perpage = 10, $cate_id = 0, $order = 'desc') {
        $cache_key = "lists_{$cate_id}_{$page}_{$perpage}_{$order}";
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['list_time'] ?? 600;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'list',
            'page' => $page,
            'perpage' => $perpage,
            'cate' => $cate_id,
            'order' => $order
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200) {
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 获取热门文章
    */
    public function hotlists($page = 1, $perpage = 10, $cate_id = 0, $days = 7) {
        $cache_key = "hotlists_{$cate_id}_{$page}_{$perpage}_{$days}";
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['list_time'] ?? 600;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'hot',
            'page' => $page,
            'perpage' => $perpage,
            'cate' => $cate_id,
            'days' => $days
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200) {
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 获取随机文章
    */
    public function randomlists($page = 1, $perpage = 10, $cate_id = 0) {
        $cache_key = "randomlists_{$cate_id}_{$page}_{$perpage}";
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['random_time'] ?? 300;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'random',
            'page' => $page,
            'perpage' => $perpage,
            'cate' => $cate_id
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200) {
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 获取作者文章列表
    */
    public function authorlists($author_id, $page = 1, $perpage = 10, $order = 'desc') {
        $cache_key = "authorlists_{$author_id}_{$page}_{$perpage}_{$order}";
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['list_time'] ?? 600;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'author',
            'author' => $author_id,
            'page' => $page,
            'perpage' => $perpage,
            'order' => $order
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200) {
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 获取文章详情 - 修复：文章标题不转义
    */
    public function get_post($post_id) {
        $cache_key = "post_{$post_id}";
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['list_time'] ?? 600;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'post',
            'id' => $post_id
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200 && isset($result['data'])) {
            // 确保文章标题和内容不被转义
            $result['data']['title'] = htmlspecialchars_decode($result['data']['title'] ?? '');
            $result['data']['content'] = htmlspecialchars_decode($result['data']['content'] ?? '');
            
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 搜索文章
    */
    public function search($keyword, $page = 1, $perpage = 10, $cate_id = 0, $order = 'desc') {
        $cache_key = "search_" . md5("{$keyword}_{$cate_id}_{$page}_{$perpage}_{$order}");
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['list_time'] ?? 600;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'search',
            'keyword' => $keyword,
            'page' => $page,
            'perpage' => $perpage,
            'cate' => $cate_id,
            'order' => $order
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200) {
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 获取分类列表
    */
    public function get_categories() {
        $cache_key = 'categories';
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['stats_time'] ?? 3600;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'categories'
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200) {
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 获取文章总数
    */
    public function get_total_posts($cate_id = 0) {
        $cache_key = "total_posts_{$cate_id}";
        
        // 安全获取缓存时间配置
        $cache_config = $GLOBALS['config']['cache'] ?? [];
        $cache_time = $cache_config['stats_time'] ?? 3600;

        $cached_data = $this->safe_cache_get($cache_key, $cache_time);
        if ($cached_data !== null) {
            return $cached_data;
        }

        $url = $this->build_url([
            'action' => 'total_posts',
            'cate' => $cate_id
        ]);

        $result = $this->request($url);

        if ($result['code'] == 200) {
            $this->safe_cache_set($cache_key, $result);
        }

        return $result;
    }

    /**
    * 强制更新所有缓存 - 优化版本，返回详细结果
    */
    public function refresh_all_cache() {
        $results = [
            'success' => [],
            'failed' => []
        ];

        // 清除所有缓存
        if ($this->cache && method_exists($this->cache, 'clear')) {
            $cleared = $this->cache->clear();
            if ($cleared > 0) {
                $results['success'][] = "清除 {$cleared} 个缓存文件";
            } else {
                $results['failed'][] = "缓存清除失败或没有缓存文件";
            }
        }

        // 重新获取分类和总数
        try {
            $categories_result = $this->get_categories();
            if ($categories_result['code'] == 200) {
                $results['success'][] = "分类列表缓存更新成功";
            } else {
                $results['failed'][] = "分类列表缓存更新失败: " . $categories_result['message'];
            }
        } catch (Exception $e) {
            $results['failed'][] = "分类列表缓存更新异常: " . $e->getMessage();
        }

        try {
            $total_result = $this->get_total_posts();
            if ($total_result['code'] == 200) {
                $results['success'][] = "文章总数缓存更新成功";
            } else {
                $results['failed'][] = "文章总数缓存更新失败: " . $total_result['message'];
            }
        } catch (Exception $e) {
            $results['failed'][] = "文章总数缓存更新异常: " . $e->getMessage();
        }

        return [
            'code' => 200,
            'message' => '缓存更新完成',
            'data' => $results
        ];
    }

    /**
    * 异步更新缓存 - 新增功能
    */
    public function async_refresh_cache() {
        // 在后台执行缓存更新
        if (function_exists('shell_exec') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
            $script_path = BASE_PATH . '/update-cache';
            $command = "php " . escapeshellarg($script_path) . " > /dev/null 2>&1 &";
            shell_exec($command);
            return [
                'code' => 200,
                'message' => '缓存更新任务已启动'
            ];
        } else {
            // 如果无法异步执行，同步执行
            return $this->refresh_all_cache();
        }
    }
}

// 全局API实例
if (!isset($GLOBALS['zblog_api'])) {
    $GLOBALS['zblog_api'] = new ZBlogAPI();
}

/**
* 快捷函数 - 增强错误处理
*/
function get_lists($page = 1, $perpage = 10, $cate_id = 0, $order = 'desc') {
    try {
        return $GLOBALS['zblog_api']->lists($page, $perpage, $cate_id, $order);
    } catch (Exception $e) {
        error_log("get_lists error: " . $e->getMessage());
        return ['code' => 500, 'message' => '获取文章列表失败'];
    }
}

function get_hotlists($page = 1, $perpage = 10, $cate_id = 0, $days = 7) {
    try {
        return $GLOBALS['zblog_api']->hotlists($page, $perpage, $cate_id, $days);
    } catch (Exception $e) {
        error_log("get_hotlists error: " . $e->getMessage());
        return ['code' => 500, 'message' => '获取热门文章失败'];
    }
}

function get_randomlists($page = 1, $perpage = 10, $cate_id = 0) {
    try {
        return $GLOBALS['zblog_api']->randomlists($page, $perpage, $cate_id);
    } catch (Exception $e) {
        error_log("get_randomlists error: " . $e->getMessage());
        return ['code' => 500, 'message' => '获取随机文章失败'];
    }
}

function get_authorlists($author_id, $page = 1, $perpage = 10, $order = 'desc') {
    try {
        return $GLOBALS['zblog_api']->authorlists($author_id, $page, $perpage, $order);
    } catch (Exception $e) {
        error_log("get_authorlists error: " . $e->getMessage());
        return ['code' => 500, 'message' => '获取作者文章失败'];
    }
}

function get_post($post_id) {
    try {
        return $GLOBALS['zblog_api']->get_post($post_id);
    } catch (Exception $e) {
        error_log("get_post error: " . $e->getMessage());
        return ['code' => 500, 'message' => '获取文章详情失败'];
    }
}

function search_posts($keyword, $page = 1, $perpage = 10, $cate_id = 0, $order = 'desc') {
    try {
        return $GLOBALS['zblog_api']->search($keyword, $page, $perpage, $cate_id, $order);
    } catch (Exception $e) {
        error_log("search_posts error: " . $e->getMessage());
        return ['code' => 500, 'message' => '搜索文章失败'];
    }
}

function get_categories() {
    try {
        return $GLOBALS['zblog_api']->get_categories();
    } catch (Exception $e) {
        error_log("get_categories error: " . $e->getMessage());
        return ['code' => 500, 'message' => '获取分类列表失败'];
    }
}

function get_total_posts($cate_id = 0) {
    try {
        return $GLOBALS['zblog_api']->get_total_posts($cate_id);
    } catch (Exception $e) {
        error_log("get_total_posts error: " . $e->getMessage());
        return ['code' => 500, 'message' => '获取文章总数失败'];
    }
}

/**
* 缓存管理函数
*/
function refresh_cache() {
    return $GLOBALS['zblog_api']->refresh_all_cache();
}

function async_refresh_cache() {
    return $GLOBALS['zblog_api']->async_refresh_cache();
}
?>