<?php
/**
 * Add recurring catalog items back to the active list when nextDueDate is today or past.
 * Run from cron after daily_export or on its own.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/grocery_helpers.php';

if (!file_exists(dirname(__DIR__) . '/.env')) {
    fwrite(STDERR, "Family Hub: .env missing.\n");
    exit(1);
}

migrateLegacyGroceriesIfNeeded();
$catalog = normalizeCatalogList(readJsonFile('grocery_catalog.json'));
$lists = normalizeGroceryLists(readJsonFile('grocery_lists.json'));
$today = gmdate('Y-m-d');
$added = 0;

foreach ($catalog as $ci => $c) {
    $next = isset($c['nextDueDate']) ? trim((string) $c['nextDueDate']) : '';
    $interval = max(0, (int) ($c['recurringIntervalDays'] ?? 0));
    if ($next === '' || $interval < 1) {
        continue;
    }
    if (strcmp($next, $today) > 0) {
        continue;
    }

    $storeId = (string) ($c['storeId'] ?? '');
    if ($storeId === '') {
        continue;
    }

    $name = trim((string) ($c['name'] ?? ''));
    if ($name === '') {
        continue;
    }

    $line = normalizeGroceryLineItem([
        'id' => bin2hex(random_bytes(8)),
        'catalogId' => (string) ($c['id'] ?? ''),
        'name' => $name,
        'description' => trim((string) ($c['description'] ?? '')),
        'size' => trim((string) ($c['defaultSize'] ?? '')),
        'quantity' => '1',
        'price' => '',
        'image' => trim((string) ($c['defaultImage'] ?? '')),
        'status' => 'active',
        'purchasedAt' => null,
        'source' => 'manual',
        'recurringIntervalDays' => $interval,
        'addedAt' => gmdate('c'),
    ]);

    if (!isset($lists['byStore'][$storeId])) {
        $lists['byStore'][$storeId] = [];
    }
    $lists['byStore'][$storeId][] = $line;

    $catalog[$ci]['nextDueDate'] = gmdate('Y-m-d', strtotime('+' . $interval . ' days'));
    $added++;
}

if ($added > 0) {
    writeJsonFile('grocery_catalog.json', $catalog);
    writeJsonFile('grocery_lists.json', $lists);
}

fwrite(STDOUT, 'grocery_recurring: added ' . $added . " item(s).\n");
