DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`payment_beforeInsert`
	BEFORE INSERT ON `payment`
	FOR EACH ROW
BEGIN
	DECLARE vBankAccount DOUBLE;
	DECLARE vSupplierAccount DOUBLE;
	DECLARE vNewBookEntry INT;
	DECLARE vIsCash BOOLEAN;
	DECLARE vIsSupplierActive BOOLEAN;

	SELECT (at2.code = 'cash') INTO vIsCash
		FROM accounting a
			JOIN accountingType at2 ON at2.id = a.accountingTypeFk
		WHERE a.id = NEW.bankFk;

	IF vIsCash THEN
		SELECT account INTO vBankAccount
			FROM accounting
			WHERE id = NEW.bankFk;
			
		SELECT account INTO vSupplierAccount
			FROM supplier
			WHERE id = NEW.supplierFk;

		CALL ledger_next(YEAR(NEW.received), vNewBookEntry);

		INSERT INTO XDiario (
				ASIEN,
				FECHA,
				SUBCTA,
				CONTRA,
				CONCEPTO,
				EURODEBE,
				EUROHABER,
				empresa_id)
			SELECT 	vNewBookEntry,
					NEW.received,
					SUBCTA,
					CONTRA,
					NEW.concept,
					EURODEBE,
					EUROHABER,
					NEW.companyFk
				FROM (SELECT vBankAccount SUBCTA,
							vSupplierAccount CONTRA,
							0 EURODEBE,
							NEW.amount + NEW.bankingFees EUROHABER
						UNION ALL
						SELECT vSupplierAccount SUBCTA,
							vBankAccount CONTRA,
							NEW.amount EURODEBE,
							0 EUROHABER) gf;

		IF NEW.bankingFees <> 0 THEN
			INSERT INTO XDiario (	
					ASIEN,
					FECHA,
					SUBCTA,
					CONTRA,
					CONCEPTO,
					EURODEBE,
					EUROHABER,
					empresa_id)
				SELECT 	vNewBookEntry,
						NEW.received,
						IF(c.id = 1,6260000002,
						IF(CEE = 1,6260000003,6260000004)),
						vBankAccount,
						NEW.concept,
						NEW.bankingFees,
						0,
						NEW.companyFk
					FROM supplier s
						JOIN country c ON s.countryFk = c.id
					WHERE s.id = NEW.supplierFk;
		END IF;		
	END IF;

	SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received);

	SELECT isActive INTO vIsSupplierActive
		FROM supplier
		WHERE id = NEW.supplierFk;
		
	IF vIsSupplierActive = FALSE THEN
		CALL util.throw('SUPPLIER_INACTIVE');
	END IF;

	IF ISNULL(NEW.workerFk) THEN
		SET NEW.workerFk = account.myUser_getId();
	END IF;
END$$
DELIMITER ;
