<?php
// ajax/workshop_transaction.ajax.php
// Handles stock check-in and check-out.
// POST params:
//   action    = 'in' | 'out'
//   stock_id  = record_id from stock table
//   quantity  = integer
//   order_no  = string (optional, for check-out)
//   notes     = string (optional)
session_start();
include $_SERVER['DOCUMENT_ROOT'] . "/root.class.php";
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['ok' => false, 'error' => 'POST required']);
    exit;
}

if (empty($_SESSION['user_id'])) {
    echo json_encode(['ok' => false, 'error' => 'Not authenticated']);
    exit;
}

$db       = new db_safeguard();
$action   = $_POST['action']   ?? '';
$stock_id = intval($_POST['stock_id']  ?? 0);
$quantity = intval($_POST['quantity']  ?? 0);
$order_no = trim($_POST['order_no']   ?? '');
$notes    = trim($_POST['notes']      ?? '');
$user_id  = intval($_SESSION['user_id']);

if (!in_array($action, ['in', 'out'])) {
    echo json_encode(['ok' => false, 'error' => 'Invalid action']);
    exit;
}
if ($stock_id <= 0 || $quantity <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Invalid stock_id or quantity']);
    exit;
}

// ── GET CURRENT STOCK ITEM ────────────────────────────────
$item_res = $db->query("stock",
    "SELECT record_id, stock_no, item_name, status
     FROM stock WHERE record_id = '$stock_id'"
);
$item = $item_res->fetch_assoc();

if (!$item) {
    echo json_encode(['ok' => false, 'error' => 'Stock item not found']);
    exit;
}

$current_qty = (int) $item['status'];

// ── CHECK-OUT: validate sufficient stock ──────────────────
if ($action === 'out' && $quantity > $current_qty) {
    echo json_encode([
        'ok'    => false,
        'error' => "Insufficient stock. Available: {$current_qty}"
    ]);
    exit;
}

// ── CALCULATE NEW QUANTITY ────────────────────────────────
$new_qty = ($action === 'in') ? $current_qty + $quantity : $current_qty - $quantity;

// ── UPDATE STOCK TABLE ────────────────────────────────────
$db->query("stock",
    "UPDATE stock SET status = '$new_qty' WHERE record_id = '$stock_id'"
);

// ── INSERT TRANSACTION RECORD ─────────────────────────────
$trans_status = ($action === 'in') ? 'IN' : 'BOOKED';
$order_sql    = $db->real_escape_string($order_no);
$notes_sql    = $db->real_escape_string($notes);
$stock_no     = $db->real_escape_string($item['stock_no']);
$item_name    = $db->real_escape_string($item['item_name']);

$db->query("stock_trans",
    "INSERT INTO stock_trans (stock_no, item_name, quantity, status, order_no)
     VALUES ('$stock_no', '$item_name', '$quantity', '$trans_status', '$order_sql')"
);

echo json_encode([
    'ok'      => true,
    'action'  => $action,
    'new_qty' => $new_qty,
    'item'    => $item['item_name'],
]);