USE `vn`;
DROP procedure IF EXISTS `ticket_componentUpdate`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_componentUpdate`(
	 vTicketFk INT,
     vClientFk INT,
     vAgencyModeFk INT,
     vAddressFk INT,
     vZoneFk INT,
     vWarehouseFk TINYINT,
     vCompanyFk SMALLINT,
     vShipped DATETIME,
     vLanded DATE,
     vIsDeleted BOOLEAN,
     vHasToBeUnrouted BOOLEAN,
     vOption INT)
BEGIN
    DECLARE vPrice DECIMAL(10,2);
    DECLARE vBonus DECIMAL(10,2);
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
        RESIGNAL;
	END;

	START TRANSACTION;
    
   IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN
			
		UPDATE ticket t 
				JOIN address a ON a.id = vAddressFk
			SET t.nickname = a.nickname
			WHERE t.id = vTicketFk;
            
    END IF;
    
    CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk);
    
	SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus 
		FROM tmp.zoneGetShipped
		WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1;
            
	UPDATE ticket t
		SET 
			t.clientFk = vClientFk,
			t.agencyModeFk = vAgencyModeFk,
			t.addressFk = vAddressFk,
            t.zoneFk = vZoneFk,
            t.zonePrice = vPrice,
            t.zoneBonus = vBonus,
			t.warehouseFk = vWarehouseFk,
            t.companyFk = vCompanyFk,
			t.landed = vLanded,
			t.shipped = vShipped,
            t.isDeleted = vIsDeleted
		WHERE
			t.id = vTicketFk;
            
	IF vHasToBeUnrouted THEN
		UPDATE ticket t SET t.routeFk = NULL
			WHERE t.id = vTicketFk;
    END IF;
            
	IF vOption <> 8 THEN
		DROP TEMPORARY TABLE IF EXISTS tmp.sale;
		CREATE TEMPORARY TABLE tmp.sale
			(PRIMARY KEY (saleFk))
            ENGINE = MEMORY
			SELECT id AS saleFk, vWarehouseFk warehouseFk
				FROM sale s WHERE s.ticketFk = vTicketFk;

		CALL ticketComponentUpdateSale (vOption);

        DROP TEMPORARY TABLE tmp.sale;
	END IF;
	COMMIT;
END$$

DELIMITER ;

