<?php
/**
 * POST /api/pantry/add.php
 * Body (JSON): { product_name, quantity?, expiry_date?, source_product_id? }
 * source_product_id is optional — set it when a pantry item was added from a
 * marketplace listing (e.g. after purchase), so it can be traced back later.
 */

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();
$missing = validate_required($input, ['product_name']);
if ($missing) {
    send_error('Product name is required.', 422);
}

$productName = trim($input['product_name']);
$quantity    = max(1, (int) ($input['quantity'] ?? 1));
$expiryDate  = !empty($input['expiry_date']) ? $input['expiry_date'] : null;
$sourceId    = !empty($input['source_product_id']) ? (int) $input['source_product_id'] : null;

if ($expiryDate && !DateTime::createFromFormat('Y-m-d', $expiryDate)) {
    send_error('Expiry date must be in YYYY-MM-DD format.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare(
    'INSERT INTO pantry_items (user_id, source_product_id, product_name, quantity, expiry_date) VALUES (?, ?, ?, ?, ?)'
);
$stmt->execute([$userId, $sourceId, $productName, $quantity, $expiryDate]);

send_json(true, 'Added to your pantry.', ['id' => (int) $pdo->lastInsertId()], 201);
