<?php
/**
 * 2026企业CMS - 微信小程序API
 * 提供RESTful API接口，用于小程序获取数据
 */

// 引入核心文件
require_once __DIR__ . '/includes/functions.php';

// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// 处理OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit;
}

// 获取请求路径
$request_uri = $_SERVER['REQUEST_URI'];
$path = str_replace('/api/', '', parse_url($request_uri, PHP_URL_PATH));
$segments = explode('/', $path);
$resource = $segments[0] ?? '';
$id = $segments[1] ?? 0;

// 获取查询参数
$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = intval($_GET['page_size'] ?? 10);
$category_id = intval($_GET['category_id'] ?? 0);

// API密钥验证（简单版本）
$api_key = $_GET['api_key'] ?? '';
$valid_api_key = get_setting('api_key', 'cms2026api');

if ($api_key !== $valid_api_key) {
    echo json_encode([
        'success' => false,
        'message' => 'API密钥错误'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// 路由处理
switch ($resource) {
    case 'articles':
        // 文章列表/详情
        if ($id > 0) {
            // 文章详情
            $article = db_query_one("SELECT a.*, ad.realname as author_name FROM `articles` a LEFT JOIN `admins` ad ON a.author_id=ad.id WHERE a.`id`=? AND a.`status`=1", [$id]);
            
            if ($article) {
                // 更新浏览量
                db_exec("UPDATE `articles` SET `views`=`views`+1 WHERE `id`=?", [$id]);
                
                echo json_encode([
                    'success' => true,
                    'data' => $article
                ], JSON_UNESCAPED_UNICODE);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => '文章不存在'
                ], JSON_UNESCAPED_UNICODE);
            }
        } else {
            // 文章列表
            $where = 'status=1';
            $params = [];
            
            if ($category_id > 0) {
                $where .= ' AND `category_id`=?';
                $params[] = $category_id;
            }
            
            $total = db_count('articles', $where, $params);
            $offset = ($page - 1) * $pageSize;
            $articles = db_query("SELECT `id`, `title`, `slug`, `summary`, `cover_image`, `views`, `published_at` FROM `articles` WHERE {$where} ORDER BY `is_top` DESC, `published_at` DESC LIMIT {$offset}, {$pageSize}", $params);
            
            echo json_encode([
                'success' => true,
                'data' => [
                    'list' => $articles,
                    'total' => $total,
                    'page' => $page,
                    'page_size' => $pageSize,
                    'total_page' => ceil($total / $pageSize)
                ]
            ], JSON_UNESCAPED_UNICODE);
        }
        break;
        
    case 'products':
        // 产品列表/详情
        if ($id > 0) {
            // 产品详情
            $product = db_query_one("SELECT * FROM `products` WHERE `id`=? AND `status`=1", [$id]);
            
            if ($product) {
                // 更新浏览量
                db_exec("UPDATE `products` SET `views`=`views`+1 WHERE `id`=?", [$id]);
                
                echo json_encode([
                    'success' => true,
                    'data' => $product
                ], JSON_UNESCAPED_UNICODE);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => '产品不存在'
                ], JSON_UNESCAPED_UNICODE);
            }
        } else {
            // 产品列表
            $where = 'status=1';
            $params = [];
            
            if ($category_id > 0) {
                $where .= ' AND `category_id`=?';
                $params[] = $category_id;
            }
            
            $total = db_count('products', $where, $params);
            $offset = ($page - 1) * $pageSize;
            $products = db_query("SELECT `id`, `title`, `slug`, `summary`, `cover_image`, `price`, `views`, `sales` FROM `products` WHERE {$where} ORDER BY `is_hot` DESC, `sort_order` ASC, `id` DESC LIMIT {$offset}, {$pageSize}", $params);
            
            echo json_encode([
                'success' => true,
                'data' => [
                    'list' => $products,
                    'total' => $total,
                    'page' => $page,
                    'page_size' => $pageSize,
                    'total_page' => ceil($total / $pageSize)
                ]
            ], JSON_UNESCAPED_UNICODE);
        }
        break;
        
    case 'categories':
        // 文章分类列表
        $categories = db_query("SELECT * FROM `categories` WHERE `status`=1 ORDER BY `sort_order` ASC, `id` ASC");
        
        echo json_encode([
            'success' => true,
            'data' => $categories
        ], JSON_UNESCAPED_UNICODE);
        break;
        
    case 'product_categories':
        // 产品分类列表
        $categories = db_query("SELECT * FROM `product_categories` WHERE `status`=1 ORDER BY `sort_order` ASC, `id` ASC");
        
        echo json_encode([
            'success' => true,
            'data' => $categories
        ], JSON_UNESCAPED_UNICODE);
        break;
        
    case 'slides':
        // 幻灯片列表
        $slides = db_query("SELECT * FROM `slides` WHERE `status`=1 ORDER BY `sort_order` ASC, `id` ASC");
        
        echo json_encode([
            'success' => true,
            'data' => $slides
        ], JSON_UNESCAPED_UNICODE);
        break;
        
    case 'pages':
        // 单页详情
        $slug = $_GET['slug'] ?? '';
        if ($slug) {
            $page = db_query_one("SELECT * FROM `pages` WHERE `slug`=? AND `status`=1", [$slug]);
        } elseif ($id > 0) {
            $page = db_query_one("SELECT * FROM `pages` WHERE `id`=? AND `status`=1", [$id]);
        } else {
            // 所有单页
            $pages = db_query("SELECT `id`, `title`, `slug` FROM `pages` WHERE `status`=1 ORDER BY `sort_order` ASC");
            
            echo json_encode([
                'success' => true,
                'data' => $pages
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
        
        if ($page) {
            echo json_encode([
                'success' => true,
                'data' => $page
            ], JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode([
                'success' => false,
                'message' => '页面不存在'
            ], JSON_UNESCAPED_UNICODE);
        }
        break;
        
    case 'search':
        // 搜索
        $keyword = trim($_GET['q'] ?? '');
        
        if (empty($keyword)) {
            echo json_encode([
                'success' => false,
                'message' => '请输入搜索关键词'
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
        
        $results = [
            'articles' => db_query("SELECT 'article' as type, `id`, `title`, `summary`, `slug` FROM `articles` WHERE `status`=1 AND (`title` LIKE ? OR `content` LIKE ?) LIMIT 10", ["%{$keyword}%", "%{$keyword}%"]),
            'products' => db_query("SELECT 'product' as type, `id`, `title`, `summary`, `slug` FROM `products` WHERE `status`=1 AND (`title` LIKE ? OR `content` LIKE ?) LIMIT 10", ["%{$keyword}%", "%{$keyword}%"])
        ];
        
        echo json_encode([
            'success' => true,
            'data' => $results
        ], JSON_UNESCAPED_UNICODE);
        break;
        
    case 'config':
        // 网站配置
        $config = [
            'site_name' => SITE_NAME,
            'site_url' => SITE_URL,
            'site_slogan' => SITE_SLOGAN,
            'contact_phone' => get_setting('contact_phone', ''),
            'contact_email' => get_setting('contact_email', ''),
            'address' => get_setting('address', ''),
            'icp_number' => get_setting('icp_number', ''),
            'seo_title' => get_setting('seo_title', ''),
            'seo_keywords' => get_setting('seo_keywords', ''),
            'seo_description' => get_setting('seo_description', '')
        ];
        
        echo json_encode([
            'success' => true,
            'data' => $config
        ], JSON_UNESCAPED_UNICODE);
        break;
        
    default:
        // 404
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => '接口不存在'
        ], JSON_UNESCAPED_UNICODE);
        break;
}

// 生成API文档
if (isset($_GET['doc'])) {
    header('Content-Type: text/html; charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>API文档 - 2026企业CMS</title>
        <style>
            body { font-family: Arial, sans-serif; padding: 40px; max-width: 1000px; margin: 0 auto; }
            h1 { color: #2c82e0; }
            h2 { margin-top: 30px; padding-bottom: 10px; border-bottom: 2px solid #2c82e0; }
            .endpoint { margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 4px; }
            .method { display: inline-block; padding: 3px 8px; border-radius: 3px; font-weight: bold; color: white; }
            .method.get { background: #28a745; }
            .method.post { background: #ffc107; }
            .path { font-family: monospace; font-size: 16px; margin-left: 10px; }
            .description { margin-top: 10px; color: #666; }
            .params { margin-top: 10px; }
            .params table { width: 100%; border-collapse: collapse; }
            .params th, .params td { padding: 8px; border: 1px solid #ddd; text-align: left; }
            .params th { background: #f8f9fa; }
        </style>
    </head>
    <body>
        <h1>2026企业CMS - API文档</h1>
        <p>所有接口需要在URL中传递<code>api_key</code>参数进行验证。</p>
        
        <h2>文章接口</h2>
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/articles</span>
            <div class="description">获取文章列表</div>
            <div class="params">
                <table>
                    <tr><th>参数</th><th>类型</th><th>说明</th></tr>
                    <tr><td>page</td><td>int</td><td>页码，默认1</td></tr>
                    <tr><td>page_size</td><td>int</td><td>每页数量，默认10</td></tr>
                    <tr><td>category_id</td><td>int</td><td>分类ID</td></tr>
                </table>
            </div>
        </div>
        
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/articles/{id}</span>
            <div class="description">获取文章详情</div>
        </div>
        
        <h2>产品接口</h2>
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/products</span>
            <div class="description">获取产品列表</div>
        </div>
        
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/products/{id}</span>
            <div class="description">获取产品详情</div>
        </div>
        
        <h2>其他接口</h2>
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/categories</span>
            <div class="description">获取文章分类</div>
        </div>
        
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/product_categories</span>
            <div class="description">获取产品分类</div>
        </div>
        
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/slides</span>
            <div class="description">获取幻灯片</div>
        </div>
        
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/pages?slug=about</span>
            <div class="description">获取单页内容</div>
        </div>
        
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/search?q=关键词</span>
            <div class="description">搜索</div>
        </div>
        
        <div class="endpoint">
            <span class="method get">GET</span>
            <span class="path">/api/config</span>
            <div class="description">获取网站配置</div>
        </div>
        
        <h2>返回格式</h2>
        <pre style="padding: 15px; background: #f8f9fa; border-radius: 4px; overflow-x: auto;">
{
    "success": true,
    "data": {...},
    "message": "可选的消息"
}
        </pre>
    </body>
    </html>
    <?php
    exit;
}
