<?php
// ─── POST /api/stock/assign.php ──────────────────────────────────────────
// Creates a booking order (book_stock + book_stock_list + stock_trans).
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();

$team_id      = (int)   ($_POST['team_id']     ?? 0);
$booking_date = str_replace('T', ' ', trim($_POST['booking_date'] ?? ''));
$pump_code    = trim($_POST['pump_code']        ?? '');
$reg_no       = trim($_POST['registration_no'] ?? '');
$items        = json_decode($_POST['items']    ?? '[]', true);

if (!$team_id)      Response::error('Team is required.');
if (!$booking_date) Response::error('Booking date is required.');
if (empty($items))  Response::error('At least one stock item is required.');

$db->run('START TRANSACTION');

// Generate order number
$count    = (int) $db->scalar("SELECT COUNT(*) FROM book_stock FOR UPDATE");
$order_no = 'SO_' . ($count + 1);

// Insert order header
$db->run(
    "INSERT INTO book_stock (order_no, team_assigned_id, booking_date, status)
     VALUES (?, ?, ?, '0')",
    [$order_no, $team_id, $booking_date]
);

$errors = [];
foreach ($items as $item) {
    $stock_no    = trim($item['stock_no']    ?? '');
    $quantity    = (int) ($item['quantity']  ?? 0);
    $type_id     = (int) ($item['type_id']   ?? 0);
    $open_bal    = (float) ($item['open_balance']  ?? 0);
    $close_bal   = (float) ($item['close_balance'] ?? 0);

    if (!$stock_no || $quantity <= 0) continue;

    // Look up item name
    $stock = $db->row("SELECT * FROM stock WHERE stock_no = ?", [$stock_no]);
    if (!$stock) { $errors[] = "Stock $stock_no not found."; continue; }

    $item_name = $stock['item_name'];

    // Insert line item
    $db->run(
        "INSERT INTO book_stock_list
            (order_no, pump_code, registration_no, stock_type_id, stock_no,
             item_name, amount, open_balance, close_balance)
         VALUES (?,?,?,?,?,?,?,?,?)",
        [$order_no, $pump_code, $reg_no, $type_id ?: $stock['stock_type_id'],
         $stock_no, $item_name, $quantity, $open_bal, $close_bal]
    );

    // Record BOOKED OUT transaction
    $db->run(
        "INSERT INTO stock_trans (stock_no, item_name, quantity, status, order_no)
         VALUES (?,?,?,'BOOKED OUT',?)",
        [$stock_no, $item_name, $quantity, $order_no]
    );
}

$db->run('COMMIT');

Response::ok(['order_no' => $order_no], 'Stock booked successfully.');