DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`client_beforeUpdate`
	BEFORE UPDATE ON `client`
	FOR EACH ROW
BEGIN
	DECLARE vText VARCHAR(255) DEFAULT NULL;
	DECLARE vPayMethodFk INT;

	SET NEW.editorFk = account.myUser_getId();

	IF NOT(NEW.credit <=> OLD.credit) THEN
		INSERT INTO clientCredit
			SET clientFk = NEW.id,
				amount = NEW.credit,
				workerFk = NEW.editorFk;
	END IF;
	-- Comprueba que el formato de los teléfonos es válido

	IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN
		CALL pbx.phone_isValid(NEW.phone);
	END IF;

	IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN
		CALL pbx.phone_isValid(NEW.mobile);
	END IF;

	SELECT id INTO vPayMethodFk
		FROM vn.payMethod
		WHERE code = 'bankDraft';

	IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN
		SET NEW.dueDay = 5;
	END IF;

	-- Avisar al comercial si ha llegado la documentación sepa/core

	IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN
		SET vText = 'Sepa de VNL';
	END IF;

	IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN
		SET vText = 'Core de VNL';
	END IF;

	IF vText IS NOT NULL
	THEN
		INSERT INTO mail(receiver, replyTo, `subject`, body)
			SELECT IFNULL(d.notificationEmail, 'jgallego@verdnatura.es'),
					'administracion@verdnatura.es',
					CONCAT('Cliente ', NEW.id),
					CONCAT('Recibida la documentación: ', vText)
				FROM department d
				WHERE d.id = NEW.departmentFk;
	END IF;


	IF NEW.departmentFk IS NULL AND OLD.departmentFk IS NOT NULL THEN
		IF (SELECT COUNT(clientFk)
				FROM clientProtected
				WHERE clientFk = NEW.id
			) > 0 THEN
			CALL util.throw("HAS_CLIENT_PROTECTED");
		END IF;
	END IF;


	IF NOT (NEW.departmentFk <=> OLD.departmentFk) THEN
		SET NEW.lastdepartmentFk = IFNULL(NEW.departmentFk, OLD.departmentFk);
	END IF;

	IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN
		SET NEW.isTaxDataChecked = 0;
	END IF;

	IF NOT (NEW.provinceFk <=> OLD.provinceFk)
		OR (NEW.postcode <=> OLD.postcode) THEN

		SET NEW.geoFk = client_getGeo(NEW.id);
	END IF;
END$$
DELIMITER ;
