<?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);
if (($actor['role'] ?? '') !== ROLE_HEAD || !isHohVerified()) {
    sendJson(['success' => false, 'error' => 'Only a verified Head of household can change the planning week'], 403);
}

$body = readJsonBody();
$weekStart = isset($body['weekStart']) ? trim((string) $body['weekStart']) : '';
if ($weekStart === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $weekStart)) {
    sendJson(['success' => false, 'error' => 'weekStart must be YYYY-MM-DD (use the Monday of the week)'], 400);
}

$plan = [
    'weekStart' => $weekStart,
    'slots' => mealDefaultEmptySlots(),
];

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

sendJson(['success' => true, 'plan' => $plan]);
