<?php
require_once 'config.php'; // Defines DATA_DIR

header('Content-Type: application/json');

// --- Get filename from query parameter ---
$requestedFile = $_GET['file'] ?? null;

if (!$requestedFile) {
    http_response_code(400); // Bad Request
    echo json_encode(['error' => 'Missing required "file" parameter.']);
    exit;
}

// --- Basic security check: prevent directory traversal ---
// Ensure the filename doesn't contain '..' and only contains expected characters.
if (strpos($requestedFile, '..') !== false || !preg_match('/^[a-z0-9_.\-]+$/i', $requestedFile)) {
    http_response_code(400); // Bad Request
    logError("Attempted directory traversal or invalid filename in get_data.php", ['requestedFile' => $requestedFile]);
    echo json_encode(['error' => 'Invalid filename requested.']);
    exit;
}

// Construct the full path
$filePath = DATA_DIR . '/' . $requestedFile;

// --- Check if file exists and read ---
if (!file_exists($filePath)) {
    http_response_code(404); // Not Found
    logError("Requested data file not found in get_data.php", ['filePath' => $filePath]);
    echo json_encode(['error' => 'Requested data file (' . htmlspecialchars($requestedFile) . ') not found. Please refresh data first.']);
    exit;
}

$jsonData = file_get_contents($filePath);

if ($jsonData === false) {
    http_response_code(500); // Internal Server Error
    logError("Failed to read data file in get_data.php", $filePath);
    echo json_encode(['error' => 'Failed to read data file.']);
    exit;
}

// --- Validate JSON before outputting ---
json_decode($jsonData); // Try decoding
if (json_last_error() !== JSON_ERROR_NONE) {
     http_response_code(500); // Internal Server Error
     logError("Failed to decode JSON data in get_data.php", ['file' => $filePath, 'error' => json_last_error_msg()]);
     echo json_encode(['error' => 'Data file contains invalid JSON.']);
     exit;
}

// --- Output the raw JSON content ---
echo $jsonData;
exit;
?>