false, 'message' => 'Acceso no autorizado.']); exit(); } $response = ['success' => false, 'message' => 'Petición 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(); $stmt_unidad = $pdo->prepare(" SELECT u.*, p.nombre as producto_nombre FROM unidades_inventario u JOIN products p ON u.producto_id = p.id WHERE u.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("La unidad no está en el almacén. Estado actual: " . $unidad['estado']); } $update_unidad_stmt = $pdo->prepare("UPDATE unidades_inventario SET estado = 'Vendido', fecha_salida = :fecha_salida WHERE id = :id"); $update_unidad_stmt->execute(['fecha_salida' => $movement_date, 'id' => $unidad['id']]); $product_id = $unidad['producto_id']; $quantity = 1; $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 && $existing_stock['quantity'] > 0) { $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 { if ($existing_stock) { $update_stock_stmt = $pdo->prepare("UPDATE stock_sedes SET quantity = 0 WHERE id = :id"); $update_stock_stmt->execute(['id' => $existing_stock['id']]); } } $history_stmt = $pdo->prepare( "INSERT INTO stock_movements (product_id, sede_id, quantity, type, movement_date) VALUES (:product_id, :sede_id, :quantity, 'salida', :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' => 'Salida de "' . $unidad['producto_nombre'] . '" registrada.']; } catch (Exception $e) { $pdo->rollBack(); $response = ['success' => false, 'message' => $e->getMessage()]; } } else { $response = ['success' => false, 'message' => 'Faltan datos: código de unidad o sede.']; } } echo json_encode($response); ?>