DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100))
proc: BEGIN
/**
 * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a workerTimeControlAdd
 *
 * @param vUserFk Identificador del trabajador
 * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ;
 *	En caso de tener algun problema retorna el primero que encuentra
 */
	DECLARE vLastIn DATETIME ;
	DECLARE vLastOut DATETIME ;
	DECLARE vDayWorkMax INT;
	DECLARE vDayBreak INT;
	DECLARE vWeekBreak INT ;
	DECLARE vWeekScope INT;
	DECLARE vDayStayMax INT;
	DECLARE vProblem VARCHAR(20) DEFAULT NULL;
	DECLARE vTimedWorked INT;
	DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL;
	DECLARE vDepartmentFk INT;
	DECLARE vTo VARCHAR(50) DEFAULT NULL;
	DECLARE vUserName VARCHAR(50) DEFAULT NULL;
	DECLARE vBody VARCHAR(255) DEFAULT NULL;
		
	SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax 
		INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax
		FROM workerTimeControlParams;

	SELECT MAX(timed) INTO vLastIn
		FROM workerTimeControl 
		WHERE userFk = vUserFk 
			AND direction = 'in';
		
	SELECT MAX(timed) INTO vLastOut
		FROM workerTimeControl 
		WHERE userFk = vUserFk 
			AND direction = 'out'; 

	SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo
		FROM account.user u
		WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk);   
		
	SELECT CONCAT(firstName,' ',lastName) INTO vUserName
		FROM worker w
		WHERE w.id = vUserFk;


	IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA
		
		-- VERIFICAR DESCANSO DIARIO 
		IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN 
			SELECT "Descansos 12 h" AS problem;
			-- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody;
				CALL mail_insert(vTo,vTo,'error al fichar',vBody);
			LEAVE proc;
		END IF;   
		
		-- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ
		IF (SELECT MOD(COUNT(*),2) -- <>0 							
				FROM workerTimeControl 
				WHERE userFk = vUserFk
					AND timed >= vLastIn
			) THEN				
			SELECT "Dias con fichadas impares" AS problem;
			-- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody;
				CALL mail_insert(vTo,vTo,'error al fichar',vBody);
			LEAVE proc;	  
		END IF;
		
		-- VERIFICAR VACACIONES
		SELECT at2.name INTO vCalendarStateType
			FROM calendar c 
				JOIN business b ON b.id = c.businessFk
				JOIN absenceType at2 ON at2.id = c.dayOffTypeFk
			WHERE c.dated = util.VN_CURDATE()
				AND at2.isAllowedToWork = FALSE
				AND b.workerFk = vUserFk
			LIMIT 1;
		
			IF(LENGTH(vCalendarStateType)) THEN
			SELECT vCalendarStateType AS problem;
			-- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody;
				CALL mail_insert(vTo,vTo,'error al fichar',vBody);
			LEAVE proc;	
				
			END IF;
		
		-- VERIFICAR CONTRATO EN VIGOR
			IF (SELECT COUNT(*)
					FROM business b
					WHERE b.workerFk = vUserFk
						AND b.started <= vDated
						AND IFNULL(b.ended, vDated) >= vDated
				) = 0 THEN
				SELECT "No hay un contrato en vigor" AS problem;
				-- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody;
				CALL mail_insert(vTo,vTo,'error al fichar',vBody);
				LEAVE proc;	
					
			END IF;

		-- VERIFICAR DESCANSO SEMANAL
		SET @vHasBreakWeek:= FALSE;
		SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); 
		
		DROP TEMPORARY TABLE IF EXISTS tmp.trash;
		CREATE TEMPORARY TABLE tmp.trash
		SELECT  IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias,
				@vLastTimed:= UNIX_TIMESTAMP(timed)
			FROM workerTimeControl 
			WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND)
				AND userFk= vUserFk
				AND direction IN ('in','out')
			ORDER BY timed ASC;   
			
		IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA     
			SELECT "Descansos 36 h" AS problem;
			-- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody;
				CALL mail_insert(vTo,vTo,'error al fichar',vBody);
			LEAVE proc;
		END IF;
		
		DROP TEMPORARY TABLE tmp.trash;    

	ELSE  -- DIA ACTUAL   
		
		-- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO
		SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) -  IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked 
			FROM workerTimeControl wtc
			WHERE userFk = vUserFk 
				AND timed >= vLastIn
			ORDER BY timed;

		IF  vTimedWorked > vDayWorkMax THEN 
			SELECT "Jornadas" AS problem;
			-- ENVIAMOS CORREO AL BOSSFK
				SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody;
				CALL mail_insert(vTo,vTo,'error al fichar',vBody);
			LEAVE proc;
		END IF;

	END IF;

		-- VERIFICAR DEPARTAMENTO
	/*	IF vTabletFk IS NOT NULL  THEN
			SELECT wtcu.departmentFk INTO vDepartmentFk
				FROM workerTimeControlUserInfo wtcu
				WHERE wtcu.userFk = vUserFk;
			IF (SELECT COUNT(td.tabletFk)
						FROM tabletDepartment td
						WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk
					) = 0 THEN
					SELECT "No perteneces a este departamento." AS problem;
					-- ENVIAMOS CORREO AL BOSSFK
					SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody;
					CALL mail_insert(vTo,vTo,'error al fichar',vBody);
					LEAVE proc;	
			END IF;
		END IF;*/
	
END$$
DELIMITER ;