<?php
// ─── POST /api/stock/create.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();

$item_name      = trim($_POST['item_name']      ?? '');
$stock_type_id  = (int) ($_POST['stock_type_id'] ?? 0);
$supplier_id    = (int) ($_POST['supplier_id']   ?? 0);
$item_price     = (float) ($_POST['item_price']  ?? 0);
$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']            ?? '');
$quantity       = (int) ($_POST['quantity']      ?? 0);

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

// Generate next stock_no: ST001, ST002 …
$last = $db->scalar("SELECT stock_no FROM stock ORDER BY record_id DESC LIMIT 1");
if ($last) {
    $num     = (int) substr($last, 2) + 1;
    $stock_no = 'ST' . str_pad($num, 3, '0', STR_PAD_LEFT);
} else {
    $stock_no = 'ST001';
}

$db->run(
    "INSERT INTO stock
        (stock_no, item_name, stock_type_id, supplier_id, item_price,
         unit_of_measure, vehicle_type, pump_code, size, type, status)
     VALUES (?,?,?,?,?,?,?,?,?,?,0)",
    [$stock_no, $item_name, $stock_type_id, $supplier_id ?: null,
     $item_price, $unit_of_measure, $vehicle_type, $pump_code, $size, $type]
);

$record_id = (int) $db->lastId();

// Record initial stock receipt if qty > 0
if ($quantity > 0) {
    $db->run(
        "INSERT INTO stock_trans (stock_no, item_name, quantity, status)
         VALUES (?, ?, ?, 'RECEIVED')",
        [$stock_no, $item_name, $quantity]
    );
}

Response::ok(['record_id' => $record_id, 'stock_no' => $stock_no], 'Stock item created.');