DROP TRIGGER IF EXISTS `vn2008`.`TicketsBeforeUpdate`;

DELIMITER $$
USE `vn2008`$$
CREATE DEFINER=`root`@`%` TRIGGER `TicketsBeforeUpdate`
	BEFORE UPDATE ON `Tickets` FOR EACH ROW
BEGIN
	DECLARE vAgency INT;
	DECLARE vEmployee INT;
    DECLARE vIsCee TINYINT;
    DECLARE vHasVies TINYINT;

	SELECT Id_Trabajador INTO vEmployee
		FROM Trabajadores WHERE user_id = account.userGetId();

	IF vEmployee IS NULL THEN
		SET vEmployee = 20;
	END IF;
    
    -- Comprobación de VIES
    
    IF NEW.empresa_id <> OLD.empresa_id THEN
    
		SELECT CEE INTO vIsCee 
			FROM Proveedores AS pr 
				INNER JOIN Paises p ON p.Id = pr.pais_id 
            WHERE Id_Proveedor = NEW.empresa_id;
            
		SELECT isVies INTO vHasVies
			FROM vn.`client` 
            WHERE id = OLD.Id_Cliente;
            
		IF vIsCee = 1 AND NOT vHasVies Then
			CALL util.throw("NO_VALID_VIES");
		END IF;
        
    END IF;
    

	IF NEW.Fecha < '2001-01-01'
	THEN
		SET NEW.Id_Ruta = NULL;

		IF NEW.Fecha < '2000-01-01' then
			SET NEW.Fecha = OLD.Fecha; 
		END IF;
		
		INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
			VALUES(17, NEW.Id_Ticket, vEmployee);
	END IF;
    
        IF NEW.isDeleted = 1 THEN
			SET NEW.Fecha = DATE_FORMAT(NEW.Fecha, '2000-%m-%d %T');
			SET NEW.landing = DATE_FORMAT(NEW.landing, '2000-%m-%d %T');
    END IF;
    
END$$
DELIMITER ;
