<?php
// ─── POST /api/stock/update.php ──────────────────────────────────────────
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

Auth::require();
$db = DB::get();

$id             = (int)   ($_POST['id']             ?? 0);
$item_name      = trim($_POST['item_name']           ?? '');
$stock_type_id  = (int)   ($_POST['stock_type_id']  ?? 0);
$supplier_id    = (int)   ($_POST['supplier_id']     ?? 0);
$item_price     = isset($_POST['item_price']) ? (float) $_POST['item_price'] : null;
$unit_of_measure= trim($_POST['unit_of_measure']     ?? '');
$vehicle_type   = trim($_POST['vehicle_type']        ?? '');
$pump_code      = trim($_POST['pump_code']           ?? '');
$size           = trim($_POST['size']                ?? '');
$type           = trim($_POST['type']                ?? '');
$receive_qty    = (int)   ($_POST['receive_qty']     ?? 0); // add more stock

if (!$id)        Response::error('id is required.');
if (!$item_name) Response::error('Item name is required.');

// Get stock_no for this item
$stock_no = $db->scalar("SELECT stock_no FROM stock WHERE record_id = ?", [$id]);
if (!$stock_no) Response::error('Stock item not found.', 404);

$priceClause = $item_price !== null ? 'item_price = ?,' : '';
$priceParam  = $item_price !== null ? [$item_price] : [];

$db->run(
    "UPDATE stock SET
        item_name = ?, stock_type_id = ?, supplier_id = ?,
        {$priceClause} unit_of_measure = ?, vehicle_type = ?,
        pump_code = ?, size = ?, type = ?
     WHERE record_id = ?",
    array_merge(
        [$item_name, $stock_type_id, $supplier_id ?: null],
        $priceParam,
        [$unit_of_measure, $vehicle_type, $pump_code, $size, $type, $id]
    )
);

// If receiving more quantity, log a RECEIVED transaction
if ($receive_qty > 0) {
    $db->run(
        "INSERT INTO stock_trans (stock_no, item_name, quantity, status)
         VALUES (?, ?, ?, 'RECEIVED')",
        [$stock_no, $item_name, $receive_qty]
    );
}

Response::ok(null, 'Stock item updated.');