<?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 import recipes'], 403);
}

$body = readJsonBody();
$data = $body;
if (isset($body['package']) && is_array($body['package'])) {
    $data = $body['package'];
}

$incomingMeals = $data['meals'] ?? null;
if (!is_array($incomingMeals) || !array_is_list($incomingMeals) || count($incomingMeals) === 0) {
    sendJson(['success' => false, 'error' => 'Invalid package: meals array required'], 400);
}

$mealsUpserted = 0;
$importedIds = [];
$normalizedRows = [];

foreach ($incomingMeals as $row) {
    if (!is_array($row) || empty($row['id']) || !is_string($row['id'])) {
        sendJson(['success' => false, 'error' => 'Invalid meal row'], 400);
    }
    $norm = normalizeMealRow($row);
    if (trim((string) ($norm['title'] ?? '')) === '') {
        sendJson(['success' => false, 'error' => 'Each meal must have a title'], 400);
    }
    $mid = (string) ($norm['id'] ?? '');
    if ($mid === '') {
        sendJson(['success' => false, 'error' => 'Invalid meal id'], 400);
    }
    $importedIds[$mid] = true;
    $normalizedRows[] = $norm;
}

$meals = migrateLegacyMealsList(normalizeMealsList(readJsonFile('meals.json')));

foreach ($normalizedRows as $norm) {
    $mid = (string) ($norm['id'] ?? '');
    $idx = findMealIndexById($meals, $mid);
    if ($idx !== null) {
        $meals[$idx] = $norm;
    } else {
        $meals[] = $norm;
    }
    $mealsUpserted++;
}

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

$plan = normalizeMealPlan(readJsonFile('meal_plans.json'));
$slotsApplied = 0;

$impPlan = $data['meal_plans'] ?? [];
$impSlots = is_array($impPlan) && isset($impPlan['slots']) && is_array($impPlan['slots'])
    ? $impPlan['slots']
    : [];

for ($i = 0; $i < 7; $i++) {
    $key = (string) $i;
    $day = $impSlots[$key] ?? $impSlots[$i] ?? [];
    if (!is_array($day)) {
        continue;
    }
    foreach (mealSlotTypes() as $mt) {
        $mid = $day[$mt] ?? null;
        if ($mid === null || $mid === '') {
            continue;
        }
        if (!is_string($mid)) {
            continue;
        }
        if (!isset($importedIds[$mid])) {
            continue;
        }
        $plan['slots'][$key][$mt] = $mid;
        $slotsApplied++;
    }
}

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

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