false, 'error' => 'Unauthorized']); } if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') { json_response(405, ['ok' => false, 'error' => 'Method Not Allowed']); } $jsonInput = file_get_contents('php://input'); if ($jsonInput === false || trim($jsonInput) === '') { json_response(400, ['ok' => false, 'error' => 'Empty payload']); } $data = json_decode($jsonInput, true, 512, JSON_THROW_ON_ERROR); if (!is_array($data) || !auth_validate_csrf_token($data['csrfToken'] ?? null)) { json_response(403, ['ok' => false, 'error' => 'Invalid security token']); } $action = trim((string) ($data['action'] ?? '')); if ($action === 'create_manufacturer') { $manufacturer = create_manufacturer( $pdo, (string) ($data['name'] ?? ''), isset($data['email']) ? (string) $data['email'] : null, isset($data['phone']) ? (string) $data['phone'] : null ); json_response(201, ['ok' => true, 'manufacturer' => $manufacturer]); } if ($action === 'update_lot') { $manufacturerPartyId = $data['manufacturerPartyId'] ?? null; $manufacturerPartyId = $manufacturerPartyId === null || $manufacturerPartyId === '' ? null : (int) $manufacturerPartyId; $updatedLot = update_stock_lot_traceability( $pdo, (int) ($data['lotId'] ?? 0), $manufacturerPartyId, isset($data['manufacturerLotNumber']) ? (string) $data['manufacturerLotNumber'] : null, isset($data['mfgDate']) ? (string) $data['mfgDate'] : null, isset($data['expiryDate']) ? (string) $data['expiryDate'] : null, isset($data['purchaseDate']) ? (string) $data['purchaseDate'] : null, (string) ($currentUser['username'] ?? $currentUser['email'] ?? 'unknown') ); json_response(200, ['ok' => true, 'lot' => $updatedLot]); } json_response(422, ['ok' => false, 'error' => 'Unsupported action']); } catch (JsonException) { json_response(400, ['ok' => false, 'error' => 'Invalid JSON payload']); } catch (InvalidArgumentException $error) { json_response(422, ['ok' => false, 'error' => $error->getMessage()]); } catch (Throwable $error) { json_response(500, ['ok' => false, 'error' => 'Internal server error: ' . $error->getMessage()]); }