false, 'message' => 'Solicitud inválida.']; if ($_SERVER['REQUEST_METHOD'] == 'POST') { $codigo_unico = filter_input(INPUT_POST, 'codigo_unico', FILTER_SANITIZE_STRING); $sede_id = filter_input(INPUT_POST, 'sede_id', FILTER_VALIDATE_INT); $movement_date = date('Y-m-d H:i:s'); if ($codigo_unico && $sede_id) { try { $pdo = db(); $pdo->beginTransaction(); // 1. Buscar la unidad de inventario $stmt_unidad = $pdo->prepare("SELECT * FROM unidades_inventario WHERE codigo_unico = :codigo_unico"); $stmt_unidad->execute(['codigo_unico' => $codigo_unico]); $unidad = $stmt_unidad->fetch(PDO::FETCH_ASSOC); if (!$unidad) { throw new Exception("El código de unidad '$codigo_unico' no existe."); } if ($unidad['estado'] === 'En Almacén') { throw new Exception("Esta unidad ya se encuentra en el almacén."); } if ($unidad['estado'] === 'Vendido') { throw new Exception("Esta unidad ya fue vendida y no puede ser ingresada nuevamente."); } // 2. Actualizar el estado de la unidad $update_unidad_stmt = $pdo->prepare("UPDATE unidades_inventario SET estado = 'En Almacén', fecha_ingreso = :fecha_ingreso WHERE id = :id"); $update_unidad_stmt->execute(['fecha_ingreso' => $movement_date, 'id' => $unidad['id']]); $product_id = $unidad['producto_id']; $quantity = 1; // 3. Actualizar o insertar en stock_sedes $stmt_stock = $pdo->prepare("SELECT * FROM stock_sedes WHERE product_id = :product_id AND sede_id = :sede_id"); $stmt_stock->execute(['product_id' => $product_id, 'sede_id' => $sede_id]); $existing_stock = $stmt_stock->fetch(); if ($existing_stock) { $new_quantity = $existing_stock['quantity'] + $quantity; $update_stock_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = :quantity WHERE id = :id"); $update_stock_stmt->execute(['quantity' => $new_quantity, 'id' => $existing_stock['id']]); } else { $insert_stock_stmt = $pdo->prepare("INSERT INTO stock_sedes (product_id, sede_id, quantity) VALUES (:product_id, :sede_id, :quantity)"); $insert_stock_stmt->execute(['product_id' => $product_id, 'sede_id' => $sede_id, 'quantity' => $quantity]); } // 4. Insertar en el historial de movimientos $history_stmt = $pdo->prepare( "INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date) VALUES (:product_id, :sede_id, :quantity, 'entrada', :movement_date)" ); $history_stmt->execute([ 'product_id' => $product_id, 'sede_id' => $sede_id, 'quantity' => $quantity, 'movement_date' => $movement_date ]); $pdo->commit(); $response = ['success' => true, 'message' => "Unidad '$codigo_unico' registrada correctamente."]; } catch (Exception $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } $response = ['success' => false, 'message' => $e->getMessage()]; } } else { $response['message'] = 'Por favor, proporcione un código de unidad y una sede.'; } } echo json_encode($response); ?>