<?php
// ─── POST /api/stock/return.php ──────────────────────────────────────────
// Processes returns and used quantities for a booking order.
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();

$order_no = trim($_POST['order_no'] ?? '');
$items    = json_decode($_POST['items'] ?? '[]', true);

if (!$order_no)   Response::error('order_no is required.');
if (empty($items)) Response::error('No items provided.');

foreach ($items as $item) {
    $stock_no    = trim($item['stock_no']    ?? '');
    $item_name   = trim($item['item_name']   ?? '');
    $return_qty  = (int) ($item['return_qty'] ?? 0);
    $used_qty    = (int) ($item['used_qty']   ?? 0);
    $outstanding = (int) ($item['outstanding'] ?? 0);

    if (!$stock_no) continue;

    // Safety: combined cannot exceed outstanding
    if ($return_qty + $used_qty > $outstanding) {
        $return_qty = $outstanding;
        $used_qty   = 0;
    }

    if ($return_qty > 0) {
        $db->run(
            "INSERT INTO stock_trans (stock_no, item_name, quantity, status, order_no)
             VALUES (?,?,?,'RETURNED',?)",
            [$stock_no, $item_name, $return_qty, $order_no]
        );
    }
    if ($used_qty > 0) {
        $db->run(
            "INSERT INTO stock_trans (stock_no, item_name, quantity, status, order_no)
             VALUES (?,?,?,'USED',?)",
            [$stock_no, $item_name, $used_qty, $order_no]
        );
    }
}

Response::ok(null, 'Return processed successfully.');