<?php
header('Access-Control-Allow-Origin: *');
// 获取用户传递的参数
$num = isset($_GET['num']) ? $_GET['num'] : 1;
$r18 = isset($_GET['r18']) ? $_GET['r18'] : 0;
$size = isset($_GET['size']) ? $_GET['size'] : 'original';
$keyword = isset($_GET['keyword']) ? $_GET['keyword'] : null;
$output = isset($_GET['output']) ? $_GET['output'] : null;

// 统一代理地址
$proxy = 'i.pixiv.re';

// 统一图库
$db = '0';

// 构建API请求URL
$api_endpoint = 'https://image.anosu.top/pixiv/json';
$params = [
    'num' => $num,
    'r18' => $r18,
    'size' => $size,
    'keyword' => $keyword,
    'proxy' => urlencode($proxy), // 统一代理地址
    'db' => urlencode($db), // 统一图库
];
$request_url = $api_endpoint . '?' . http_build_query($params);

// 获取JSON数据
$json_data = @file_get_contents($request_url);

if ($json_data !== false) {
    // 解析JSON数据
    $images = json_decode($json_data, true);

    if ($output === 'json') {
        // 设置响应头为JSON格式
        header('Content-Type: application/json');

        // 构建数组
        $formatted_images = [];
        foreach ($images as $image) {
            $formatted_images[] = [
                'pid' => $image['pid'],
                'uid' => $image['uid'],
                'title' => $image['title'],
                'user' => $image['user'],
                'tags' => $image['tags'],
                'url' => $image['url'],
            ];
        }

        // 输出图片信息数组
        echo json_encode(['images' => $formatted_images]);
        exit; // 结束脚本，确保仅输出JSON数据
    } else {
        // 302跳转
        if (!empty($images) && isset($images[0]['url'])) {
            header('Location: ' . $images[0]['url'], true, 302);
            exit;
        } else {
            header("HTTP/1.1 500 Internal Server Error");
            echo '无法获取图片';
        }
    }
} else {
    // 处理无法获取JSON数据的情况
    header("HTTP/1.1 500 Internal Server Error");
    echo '出现错误';
}

?>