<?php

require_once __DIR__ . '/../includes/api_bootstrap.php';
require_once __DIR__ . '/../includes/meal_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendJson(['success' => false, 'error' => 'Method not allowed'], 405);
}

$people = normalizePeopleList(readJsonFile('people.json'));
$actor = requireActivePerson($people);
$actorId = (string) ($actor['id'] ?? '');

$body = readJsonBody();
$id = isset($body['id']) ? trim((string) $body['id']) : '';
if ($id === '') {
    sendJson(['success' => false, 'error' => 'id is required'], 400);
}

$meals = migrateLegacyMealsList(normalizeMealsList(readJsonFile('meals.json')));
$idx = findMealIndexById($meals, $id);
if ($idx === null) {
    sendJson(['success' => false, 'error' => 'Meal not found'], 404);
}

$existing = $meals[$idx];
$isAuthor = ($existing['author_id'] ?? '') === $actorId;
$isHoH = ($actor['role'] ?? '') === ROLE_HEAD && isHohVerified();
if (!$isAuthor && !$isHoH) {
    sendJson(['success' => false, 'error' => 'You cannot delete this meal'], 403);
}

array_splice($meals, $idx, 1);

if (!writeJsonFile('meals.json', $meals)) {
    sendJson(['success' => false, 'error' => 'Failed to save meals'], 500);
}

sendJson(['success' => true]);
