ALTER TABLE `vn`.`client` MODIFY COLUMN `credit` decimal(10,2) unsigned DEFAULT 0.00 NOT NULL;

DELETE FROM `salix`.`ACL` WHERE `model` = 'Client' AND `property` = 'create';

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`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
					CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'),
                    'administracion@verdnatura.es',
                    CONCAT('Cliente ', NEW.id),
					CONCAT('Recibida la documentación: ', vText)
				FROM worker w
					LEFT JOIN account.user u ON w.id = u.id AND u.active
					LEFT JOIN account.account ac ON ac.id = u.id
				WHERE w.id = NEW.salesPersonFk;
	END IF;

    IF NEW.salespersonFk IS NULL AND OLD.salespersonFk 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 !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN
		SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk);
	END IF;

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

DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeInsert`
	BEFORE INSERT ON `client`
	FOR EACH ROW
BEGIN
	IF NEW.credit NOT NULL AND NEW.credit THEN
		INSERT INTO clientCredit
			SET clientFk = NEW.id,
				workerFk = NEW.editorFk,
				amount = NEW.credit;
	END IF;

	SET NEW.editorFk = account.myUser_getId();

	IF (NEW.phone <> '') THEN
		CALL pbx.phone_isValid(NEW.phone);
	END IF;

	IF (NEW.mobile <> '') THEN
		CALL pbx.phone_isValid(NEW.mobile);
	END IF;

	SET NEW.accountingAccount = 4300000000 + NEW.id;
    
    SET NEW.lastSalesPersonFk = NEW.salesPersonFk;
END$$
DELIMITER ;

