DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCalendar_calculateBusiness`(vYear INT, vBusinessFk INT)
BEGIN
/**
 * Calcula los días y horas de vacaciones en función de un contrato y año
 *
 * @param vYear
 * @param vBusinessFk  
 * @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed)
 */
	DECLARE vStarted DATE;
	DECLARE vEnded DATE;
	DECLARE vDaysHoliday DECIMAL(5,2);
	DECLARE vHoursWeek DECIMAL(5,2);
	DECLARE vDaysToSubtract DECIMAL(5,2);
	DECLARE vDaysHolidayEnjoyed DECIMAL(5,2);
	DECLARE vPayedHolidays DECIMAL(5,2);
	DECLARE vDifDays INT;

	SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), 
					IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), 
					IF(wbt.hasHolidayEntitlement, w.days, 0),
					c.hoursWeek,
					IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays
				INTO vStarted, 
					vEnded, 
					vDaysHoliday, 
					vHoursWeek,
					vPayedHolidays
			FROM business b 
				JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk
				JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk
				LEFT JOIN calendarType c ON c.id = b.calendarTypeFk
			WHERE b.id = vBusinessFk
				AND w.year = vYear;

	DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness;
	
	IF vStarted < vEnded THEN
		SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1;

		SELECT IFNULL(SUM(a.holidayEntitlementRate), 0), 
				SUM(-(a.discountRate - 1)) + vPayedHolidays
				INTO vDaysToSubtract, 
					vDaysHolidayEnjoyed 
			FROM calendar c
				JOIN absenceType a ON a.id = c.dayOffTypeFk
				JOIN business b ON b.id = c.businessFk
			WHERE b.id = vBusinessFk 
				AND YEAR(c.dated) = vYear;

	END IF;

	CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness	
		ENGINE = MEMORY
		SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days,
			@days * (vHoursWeek / 5) hours,
			@daysEnjoyed := IFNULL(ROUND(vDaysHolidayEnjoyed, 1), 0) daysEnjoyed,
			@daysEnjoyed * (vHoursWeek / 5) hoursEnjoyed;
END$$
DELIMITER ;
