<?php
/**
 * POST /api/requests/create.php
 * Body (JSON): { item_name, category_id?, description?, desired_quantity? }
 * Any logged-in account can post a request - a personal buyer wanting
 * something not currently listed, or even a business sourcing stock.
 */

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();
$itemName = trim($input['item_name'] ?? '');
if ($itemName === '') {
    send_error('Please describe what you\'re looking for.', 422);
}

$categoryId = !empty($input['category_id']) ? (int) $input['category_id'] : null;
$description = trim($input['description'] ?? '');
$quantity = max(1, (int) ($input['desired_quantity'] ?? 1));

$pdo = Database::connect();
$stmt = $pdo->prepare(
    'INSERT INTO item_requests (requester_id, item_name, category_id, description, desired_quantity) VALUES (?, ?, ?, ?, ?)'
);
$stmt->execute([$userId, $itemName, $categoryId, $description ?: null, $quantity]);

send_json(true, 'Request posted.', ['id' => (int) $pdo->lastInsertId()], 201);
