<?php
/**
 * POST /api/pantry/remove.php
 * Body (JSON): { id }
 */

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 remove your own pantry items.', 403);
}

$stmt = $pdo->prepare('DELETE FROM pantry_items WHERE id = ?');
$stmt->execute([$id]);

send_json(true, 'Removed from your pantry.');
