' . __('fill_all_required_fields') . ''; } else { try { $db->beginTransaction(); if ($type === 'in') { // Create New Batch $batch_number = $_POST['batch_number'] ?? date('YmdHis'); $expiry_date = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null; $cost_price = $_POST['cost_price'] ?? 0; $supplier_id = !empty($_POST['supplier_id']) ? $_POST['supplier_id'] : null; $stmt = $db->prepare("INSERT INTO inventory_batches (item_id, batch_number, expiry_date, quantity, cost_price, supplier_id, received_date) VALUES (?, ?, ?, ?, ?, ?, NOW())"); $stmt->execute([$item_id, $batch_number, $expiry_date, $quantity, $cost_price, $supplier_id]); $batch_id = $db->lastInsertId(); // Create Transaction Record $stmt = $db->prepare("INSERT INTO inventory_transactions (item_id, batch_id, transaction_type, quantity, reference_type, reference_id, user_id, notes) VALUES (?, ?, 'in', ?, ?, ?, ?, ?)"); $stmt->execute([$item_id, $batch_id, $quantity, $reference_type, $reference_id, $_SESSION['user_id'], $notes]); } elseif ($type === 'out') { // Deduct from Batch $batch_id = $_POST['batch_id'] ?? 0; // Check availability $stmt = $db->prepare("SELECT quantity FROM inventory_batches WHERE id = ? FOR UPDATE"); $stmt->execute([$batch_id]); $current_qty = $stmt->fetchColumn(); if ($current_qty < $quantity) { throw new Exception(__('insufficient_stock_in_batch')); } // Update Batch $stmt = $db->prepare("UPDATE inventory_batches SET quantity = quantity - ? WHERE id = ?"); $stmt->execute([$quantity, $batch_id]); // Create Transaction Record $stmt = $db->prepare("INSERT INTO inventory_transactions (item_id, batch_id, transaction_type, quantity, reference_type, reference_id, user_id, notes) VALUES (?, ?, 'out', ?, ?, ?, ?, ?)"); $stmt->execute([$item_id, $batch_id, $quantity, $reference_type, $reference_id, $_SESSION['user_id'], $notes]); } $db->commit(); $_SESSION['flash_message'] = '