false, 'message' => 'Petición inválida.']; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $sede_id = isset($_POST['sede_id']) ? filter_var($_POST['sede_id'], FILTER_VALIDATE_INT) : null; $product_id = isset($_POST['product_id']) ? filter_var($_POST['product_id'], FILTER_VALIDATE_INT) : null; $quantity = isset($_POST['quantity']) ? filter_var($_POST['quantity'], FILTER_VALIDATE_INT) : null; if (!$sede_id || !$product_id || !$quantity || $quantity <= 0) { $response['message'] = 'Datos inválidos. Por favor, complete todos los campos correctamente.'; echo json_encode($response); exit; } try { $pdo = db(); $pdo->beginTransaction(); // 1. Verificar stock actual $sql_check = "SELECT cantidad FROM stock_sedes WHERE id_producto = :product_id AND id_sede = :sede_id FOR UPDATE"; $stmt_check = $pdo->prepare($sql_check); $stmt_check->bindParam(':product_id', $product_id, PDO::PARAM_INT); $stmt_check->bindParam(':sede_id', $sede_id, PDO::PARAM_INT); $stmt_check->execute(); $current_stock_row = $stmt_check->fetch(PDO::FETCH_ASSOC); $current_stock = $current_stock_row ? (int)$current_stock_row['cantidad'] : 0; if ($current_stock < $quantity) { $response['message'] = "Stock insuficiente. Stock actual: {$current_stock} unidades."; $pdo->rollBack(); echo json_encode($response); exit; } // 2. Actualizar stock_sedes $sql_update = "UPDATE stock_sedes SET cantidad = cantidad - :quantity WHERE id_producto = :product_id AND id_sede = :sede_id"; $stmt_update = $pdo->prepare($sql_update); $stmt_update->bindParam(':quantity', $quantity, PDO::PARAM_INT); $stmt_update->bindParam(':product_id', $product_id, PDO::PARAM_INT); $stmt_update->bindParam(':sede_id', $sede_id, PDO::PARAM_INT); $stmt_update->execute(); // 3. Registrar el movimiento $sql_movement = "INSERT INTO stock_movements (product_id, sede_id, tipo_movimiento, cantidad, origen) VALUES (:product_id, :sede_id, 'salida', :quantity, 'manual')"; $stmt_movement = $pdo->prepare($sql_movement); $stmt_movement->bindParam(':product_id', $product_id, PDO::PARAM_INT); $stmt_movement->bindParam(':sede_id', $sede_id, PDO::PARAM_INT); $stmt_movement->bindParam(':quantity', $quantity, PDO::PARAM_INT); $stmt_movement->execute(); $pdo->commit(); $response['success'] = true; $response['message'] = "Se han retirado {$quantity} unidades del stock correctamente."; } catch (PDOException $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } error_log("Error en registrar_salida_manual_api.php: " . $e->getMessage()); $response['message'] = 'Error en la base de datos. No se pudo registrar la salida.'; } } else { $response['message'] = 'Método no permitido.'; } echo json_encode($response); ?>