beginTransaction(); // 1. Insert product $sku = 'SKU-' . strtoupper(substr(uniqid(), -8)); $sql_producto = "INSERT INTO productos (sku, nombre, descripcion, costo, precio_venta, created_at) VALUES (?, ?, ?, ?, ?, NOW())"; $stmt_producto = $pdo->prepare($sql_producto); $stmt_producto->execute([$sku, $nombre, $descripcion, $costo, $precio_venta]); // Get the ID of the new product $producto_id = $pdo->lastInsertId(); // 2. Insert stock for each city $sql_stock = "INSERT INTO stock_por_ciudad (producto_id, ciudad_id, stock_actual) VALUES (?, ?, ?)"; $stmt_stock = $pdo->prepare($sql_stock); foreach ($stocks_por_ciudad as $ciudad_id => $cantidad) { $ciudad_id_int = filter_var($ciudad_id, FILTER_VALIDATE_INT); $cantidad_int = filter_var($cantidad, FILTER_VALIDATE_INT); // Only insert if stock is greater than 0 and IDs are valid if ($ciudad_id_int && $cantidad_int > 0) { $stmt_stock->execute([$producto_id, $ciudad_id_int, $cantidad_int]); } } // If all is well, commit the transaction $pdo->commit(); $_SESSION['success_message'] = "Producto y stock por ciudad agregados exitosamente."; } catch (PDOException $e) { // If something goes wrong, roll back the transaction if ($pdo->inTransaction()) { $pdo->rollBack(); } // Log error properly in a real application $_SESSION['error_message'] = "Error al agregar el producto. Detalles: " . $e->getMessage(); } } else { $_SESSION['error_message'] = "Datos de producto inválidos. Por favor, revisa el formulario."; } } else { $_SESSION['error_message'] = "Método no permitido."; } // Redirect back to the products page header("Location: productos.php"); exit();