<?php
/**
 * POST /api/pantry/update.php
 * Body (JSON): { id, product_name?, quantity?, expiry_date? }
 * Owner-only. Send only the fields that changed.
 */

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

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$id = (int) ($input['id'] ?? 0);
if ($id <= 0) {
    send_error('A valid pantry item id is required.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT user_id FROM pantry_items WHERE id = ?');
$stmt->execute([$id]);
$item = $stmt->fetch();

if (!$item) {
    send_error('Pantry item not found.', 404);
}
if ((int) $item['user_id'] !== $userId) {
    send_error('You can only edit your own pantry items.', 403);
}

$fieldMap = ['product_name' => 'product_name', 'quantity' => 'quantity', 'expiry_date' => 'expiry_date'];
$set = [];
$params = [];

foreach ($fieldMap as $key => $column) {
    if (!array_key_exists($key, $input)) {
        continue;
    }
    $value = $input[$key];

    if ($key === 'product_name' && trim((string) $value) === '') {
        send_error('Product name cannot be empty.', 422);
    }
    if ($key === 'quantity') {
        $value = max(1, (int) $value);
    }
    if ($key === 'expiry_date') {
        $value = $value === '' ? null : $value;
        if ($value && !DateTime::createFromFormat('Y-m-d', $value)) {
            send_error('Expiry date must be in YYYY-MM-DD format.', 422);
        }
    }

    $set[] = "$column = ?";
    $params[] = $value;
}

if ($set) {
    $params[] = $id;
    $sql = 'UPDATE pantry_items SET ' . implode(', ', $set) . ' WHERE id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
}

send_json(true, 'Pantry item updated.');
