<?php
// ══════════════════════════════════════════════════════════
//  list_submissions.php  —  legacy endpoint, add CORS only
//  Upload to: tmudd.net/email_writing/list_submissions.php
// ══════════════════════════════════════════════════════════

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$is_netlify = (bool) preg_match('/^https:\/\/[a-zA-Z0-9\-]+\.netlify\.app$/', $origin);
$is_same    = in_array($origin, ['https://tmudd.net', 'http://tmudd.net', '']);

if ($is_netlify || $is_same) {
    header("Access-Control-Allow-Origin: " . ($origin ?: 'https://tmudd.net'));
} else {
    header("Access-Control-Allow-Origin: https://tmudd.net");
}
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

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

$data_file = __DIR__ . '/submissions.json';
if (!file_exists($data_file)) {
    echo json_encode(['students' => []]);
    exit();
}
$raw    = file_get_contents($data_file);
$parsed = json_decode($raw, true);
echo $parsed ? $raw : json_encode(['students' => []]);
