DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`roadmap_beforeUpdate`
	BEFORE UPDATE ON `roadmap`
	FOR EACH ROW
BEGIN
	DECLARE vSeconds INT;

	SET NEW.editorFk = account.myUser_getId();

	IF NOT (NEW.name <=> OLD.name) THEN
		SET NEW.name = UCASE(NEW.name);
	END IF;

	IF NOT (NEW.trailerPlate <=> OLD.trailerPlate) OR NOT (NEW.tugPlate <=> OLD.tugPlate) THEN
		SET NEW.m3 = (SELECT SUM(m3) FROM vehicle WHERE numberPlate IN (NEW.trailerPlate, NEW.tugPlate));
	END IF;

	IF NOT (NEW.driverName <=> OLD.driverName) THEN
		SET NEW.driver1Fk = NULL;
	END IF;

	IF NOT (NEW.driver1Fk <=> OLD.driver1Fk) AND NEW.driver1Fk IS NOT NULL THEN
		SET NEW.driverName = (SELECT CONCAT(w.firstName, ' ', w.lastName)
								FROM worker w
								WHERE w.id = NEW.driver1Fk);

		SET NEW.phone = (SELECT COALESCE(w.phone, c.mobile, c.phone, c.mobile)
							FROM worker w
								LEFT JOIN client c ON c.id = w.id
							WHERE w.id = NEW.driver1Fk);
	END IF;

	IF NOT (NEW.driverChangeName <=> OLD.driverChangeName) THEN
		SET NEW.driverChangeFk = NULL;
	END IF;

	IF NOT (NEW.driverChangeFk <=> OLD.driverChangeFk) AND NEW.driverChangeFk IS NOT NULL THEN
		SET NEW.driverChangeName = (SELECT CONCAT(w.firstName, ' ', w.lastName)
										FROM worker w
										WHERE w.id = NEW.driverChangeFk);
	END IF;

	IF NOT (NEW.etd <=> OLD.etd) THEN
		SET vSeconds = TIME_TO_SEC(TIMEDIFF(NEW.etd, OLD.etd));
		
		IF vSeconds <> 0 THEN
			UPDATE roadmapStop
				SET eta = eta + INTERVAL vSeconds SECOND
				WHERE roadmapFk = NEW.id;
		END IF;
	END IF;
END$$
DELIMITER ;