<?php
/**
 * GET /api/pantry/list.php
 * Returns the caller's pantry items, soonest-expiring first (nulls last).
 * Each item is tagged with an expiry_state: expired | soon (<=3 days) | ok | none.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

$userId = require_login();

$pdo = Database::connect();
$stmt = $pdo->prepare(
    'SELECT id, product_name, quantity, expiry_date, source_product_id, created_at
     FROM pantry_items
     WHERE user_id = ?
     ORDER BY (expiry_date IS NULL), expiry_date ASC'
);
$stmt->execute([$userId]);
$items = $stmt->fetchAll();

$today = new DateTime('today');

foreach ($items as &$item) {
    if (!$item['expiry_date']) {
        $item['expiry_state'] = 'none';
        $item['days_until_expiry'] = null;
        continue;
    }
    $expiry = new DateTime($item['expiry_date']);
    $diff = (int) $today->diff($expiry)->format('%r%a'); // signed day difference
    $item['days_until_expiry'] = $diff;
    if ($diff < 0) {
        $item['expiry_state'] = 'expired';
    } elseif ($diff <= 3) {
        $item['expiry_state'] = 'soon';
    } else {
        $item['expiry_state'] = 'ok';
    }
}

send_json(true, 'OK', ['items' => $items]);
