<?php
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$dataFile = dirname(__DIR__) . '/data/works.json';
$works = [];
if (file_exists($dataFile)) {
    $works = json_decode(file_get_contents($dataFile), true) ?: [];
}

$baseUrl = 'https://beethoven.co.jp/casestudies/uploads/';

// publishToCorporate === true のデータだけ抽出
$public = array_values(array_filter($works, fn($w) => !empty($w['publishToCorporate'])));

// 必要フィールドのみ返却 + photosをフルURLに変換
$public = array_map(function($w) use ($baseUrl) {
    return [
        'id'          => $w['id'] ?? '',
        'title'       => $w['title'] ?? '',
        'category'    => $w['category'] ?? '',
        'categories'  => $w['categories'] ?? [],
        'industry'    => $w['industry'] ?? '',
        'client'      => $w['client'] ?? '',
        'description' => $w['description'] ?? '',
        'result'      => $w['result'] ?? '',
        'scope'       => $w['scope'] ?? '',
        'websiteUrl'  => $w['websiteUrl'] ?? '',
        'youtubeUrl'  => $w['youtubeUrl'] ?? '',
        'photos'      => array_map(fn($p) => $baseUrl . basename($p), $w['photos'] ?? []),
        'date'        => $w['date'] ?? '',
    ];
}, $public);

echo json_encode(array_reverse($public), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
