<?php
// POST /api/stock/receive.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireRole([1, 4]);
$db   = getDB();

$stockItemId = (int)post('stock_item_id', 0);
$locationId  = (int)post('location_id', 0);
$quantity    = (float)post('quantity', 0);

if (!$stockItemId) apiError('Stock item required.', 422);
if (!$locationId)  apiError('Location required.', 422);
if ($quantity <= 0) apiError('Quantity must be positive.', 422);

// Upsert inventory
$db->prepare("
    INSERT INTO stock_inventory (stock_item_id, location_id, quantity)
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)
")->execute([$stockItemId, $locationId, $quantity]);

// Log transaction
$db->prepare("
    INSERT INTO stock_transactions (stock_item_id, transaction_type, quantity, to_location, reference_no, notes, unit_cost, user_id)
    VALUES (?, 'receive', ?, ?, ?, ?, ?, ?)
")->execute([
    $stockItemId, $quantity, $locationId,
    post('reference_no'), post('notes'),
    post('unit_cost') ?: null,
    $user['id']
]);

apiSuccess([], 'Stock received.');
