<?php
/**
 * 系统资源获取API - 程序列表获取接口
 * 用于其他系统获取本系统的程序资源
 */

require_once __DIR__ . '/../MPHX/common.php';

header('Content-Type: application/json; charset=UTF-8');

// 获取API密钥
$api_key = isset($_GET['key']) ? trim($_GET['key']) : '';
if (empty($api_key)) {
    http_response_code(401);
    exit(json_encode(array(
        'status' => false,
        'code' => 401,
        'message' => '缺少API密钥'
    )));
}

// 验证API密钥
$key_info = $DB->get_row("SELECT * FROM `system_api_keys` WHERE `api_key`='" . daddslashes($api_key) . "' AND `status`=1");
if (!$key_info) {
    http_response_code(403);
    exit(json_encode(array(
        'status' => false,
        'code' => 403,
        'message' => 'API密钥无效或已禁用'
    )));
}

// 更新使用记录
$DB->query("UPDATE `system_api_keys` SET `use_count`=`use_count`+1, `last_used_at`=NOW() WHERE `id`=" . intval($key_info['id']));

// 生成临时下载令牌的函数
function generateDownloadToken($api_key, $filename) {
    return hash('sha256', $api_key . $filename . date('YmdH'));
}

// 获取所有程序分类
$categories = array();
$cat_res = $DB->query("SELECT * FROM `program_categories` ORDER BY `sort_order` ASC, `id` ASC");
while ($cat = $DB->fetch($cat_res)) {
    $categories[$cat['name']] = array(
        'id' => intval($cat['id']),
        'name' => $cat['name'],
        'icon' => $cat['icon'],
        'sort_order' => intval($cat['sort_order'])
    );
}

// 获取所有程序（包括所有字段）
$programs = array();
$prog_res = $DB->query("SELECT * FROM `bs` ORDER BY id DESC");
while ($prog = $DB->fetch($prog_res)) {
    $program_data = array(
        'id' => intval($prog['id']),
        'name' => $prog['name'],
        'type' => $prog['type'],
        'version' => $prog['version'],
        'form_fields' => $prog['form_fields'],
        'install_ops' => $prog['install_ops'],
        'php_version' => $prog['php_version'],
        'status' => intval($prog['status']),
        // 新增字段：用于文件同步
        'tb' => $prog['tb'],
        'wj' => $prog['wj'],
        'images' => $prog['images'],
        'js' => $prog['js'],
        'pz' => $prog['pz'],
        'jg' => $prog['jg'],
        'ybd' => $prog['ybd'],
        'pzsj' => $prog['pzsj'],
        'wcts' => $prog['wcts'],
        'webkj' => $prog['webkj'],
        'sqlkj' => $prog['sqlkj'],
        'alerts' => $prog['alerts'],
        'cover' => $prog['cover'],
        'php_ext' => $prog['php_ext']
    );

    // 解析JSON字段
    $json_fields = array('form_fields', 'install_ops', 'images');
    foreach ($json_fields as $field) {
        if (!empty($program_data[$field])) {
            // 使用 parse_json_safe 函数安全解析JSON
            $decoded = parse_json_safe($program_data[$field], true);
            if ($decoded !== null) {
                $program_data[$field] = $decoded;
            }
        }
    }

    // 为文件生成临时下载令牌
    if (!empty($program_data['tb'])) {
        $program_data['tb_token'] = generateDownloadToken($api_key, $program_data['tb']);
    }
    if (!empty($program_data['wj'])) {
        $program_data['wj_token'] = generateDownloadToken($api_key, $program_data['wj']);
    }
    if (!empty($program_data['images'])) {
        $images = is_array($program_data['images']) ? $program_data['images'] : json_decode($program_data['images'], true);
        if (is_array($images)) {
            $program_data['image_tokens'] = array();
            foreach ($images as $img) {
                $program_data['image_tokens'][$img] = generateDownloadToken($api_key, $img);
            }
        }
    }

    $programs[] = $program_data;
}

// 构建响应数据
$response = array(
    'status' => true,
    'code' => 200,
    'message' => '获取成功',
    'data' => array(
        'categories' => array_values($categories),
        'programs' => $programs,
        'total' => count($programs),
        'category_count' => count($categories)
    ),
    'meta' => array(
        'api_version' => '1.0',
        'timestamp' => date('Y-m-d H:i:s'),
        'server_time' => time()
    )
);

exit(json_encode($response, JSON_UNESCAPED_UNICODE));
?>