DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`recobro_credito`()
BEGIN
	DECLARE EXIT HANDLER FOR SQLSTATE '45000'
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;
	UPDATE vn.`client` c
			JOIN vn.payMethod pm ON pm.id = c.payMethodFk
		SET credit = 0
			WHERE pm.`code` = 'card';

	DROP TEMPORARY TABLE IF EXISTS clientes_credit;
	CREATE TEMPORARY TABLE clientes_credit
		SELECT Id_Cliente, if (Credito > Recobro ,Credito - Recobro,0) AS newCredit
		FROM (
			SELECT r.Id_Cliente, r.amount AS Recobro,
				timestampadd(DAY, period, UltimaFecha) AS Deadline, sub2.amount AS Credito
				FROM vn2008.recovery r
					JOIN (
						SELECT Id_Cliente, amount , odbc_date AS UltimaFecha
						FROM (
							SELECT * FROM credit
								ORDER BY odbc_date DESC
								LIMIT 10000000000000000000
						) sub
						GROUP BY Id_Cliente
					) sub2 USING(Id_Cliente)
				WHERE dend IS NULL or dend >= util.VN_CURDATE()
				GROUP BY Id_Cliente
					HAVING Deadline <= util.VN_CURDATE()
		) sub3
		WHERE Credito > 0;

	UPDATE Clientes
		JOIN clientes_credit USING(Id_Cliente)
			SET Clientes.Credito = newCredit;
	
	DROP TEMPORARY TABLE clientes_credit;
	COMMIT;
END$$
DELIMITER ;
