DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleSplit`(vSaleFk INT, vQuantity INT)
BEGIN

	
    DECLARE vNewSaleFk INT;
        
    INSERT INTO vn.sale(itemFk, 
						concept, 
                        price, 
                        discount, 
                        quantity, 
                        ticketFk, 
                        isPriceFixed)
		SELECT 	s.itemFk, 
				i.longName, 
                s.price, 
                s.discount, 
                vQuantity,
                s.ticketFk, 
                s.isPriceFixed 
			FROM vn.sale s
				JOIN vn.item i ON i.id = s.itemFk
				WHERE s.id = vSaleFk;
                
	UPDATE vn.sale s
		JOIN vn.item i ON i.id = s.itemFk
		SET s.quantity = s.quantity - vQuantity, s.concept = i.longName
        WHERE s.id = vSaleFk;
 
	SELECT LAST_INSERT_ID() INTO vNewSaleFk;
             
	INSERT INTO vn.saleComponent(	saleFk, 
									componentFk, 
                                    value)
	SELECT 	vNewSaleFk, 
			componentFk, 
			value
		FROM vn.saleComponent 
		WHERE saleFk = vSaleFk;

END$$
DELIMITER ;
