DROP TRIGGER IF EXISTS `vn`.`expedition_beforeInsert`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` TRIGGER `vn`.`expedition_beforeInsert`
	BEFORE INSERT ON `expedition` FOR EACH ROW
BEGIN
	DECLARE intcounter INT;
    DECLARE vShipFk INT;

	IF NEW.isBox > 0 THEN 

		UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk;

		SELECT IFNULL(MAX(counter),0) +1 INTO intcounter 
            FROM expedition e 
				INNER JOIN ticket t1 ON e.ticketFk = t1.id 
                LEFT JOIN ticketState ts ON ts.ticket = t1.id
				INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) 
                    AND t1.warehouseFk = t2.warehouseFk
			WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk 
                AND t1.agencyModeFk = t2.agencyModeFk;

		SET NEW.`counter` = intcounter;
	END IF;
    
    SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk;

    IF vShipFk THEN
		CALL stowaway_unboarding(vShipFk, NEW.ticketFk);
    END IF;
END$$
DELIMITER ;
