<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$menuFile = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'menu-data.json';

function send_json(int $status, array $payload): void
{
    http_response_code($status);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    exit;
}

function read_menu(string $path): array
{
    if (!file_exists($path)) {
        return [];
    }

    $raw = file_get_contents($path);
    if ($raw === false || trim($raw) === '') {
        return [];
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        return [];
    }

    return $decoded;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!file_exists($menuFile)) {
        send_json(404, ['error' => 'menu-data.json no encontrado']);
    }

    $data = read_menu($menuFile);
    if ($data === []) {
        send_json(500, ['error' => 'menu-data.json inválido o vacío']);
    }

    send_json(200, $data);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rawBody = file_get_contents('php://input');
    if ($rawBody === false || trim($rawBody) === '') {
        send_json(400, ['error' => 'Body vacío']);
    }

    $decoded = json_decode($rawBody, true);
    if (!is_array($decoded)) {
        send_json(400, ['error' => 'JSON inválido']);
    }

    $encoded = json_encode(
        $decoded,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
    );

    if ($encoded === false) {
        send_json(500, ['error' => 'No se pudo codificar JSON']);
    }

    $result = file_put_contents($menuFile, $encoded . PHP_EOL, LOCK_EX);
    if ($result === false) {
        send_json(500, ['error' => 'No se pudo escribir menu-data.json']);
    }

    send_json(200, ['saved' => true, 'file' => 'menu-data.json']);
}

send_json(405, ['error' => 'Método no permitido']);
