DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getCollisions`()
BEGIN
/**
 * Calcula si para un mismo codigo postal y dia 
 * hay mas de una zona configurada y manda correo
 *
 */
	DECLARE vGeoFk INT DEFAULT NULL;
	DECLARE vZoneFk INT;
	DECLARE vIsDone INT DEFAULT FALSE;
	DECLARE vTableCollisions TEXT;
	DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption;
		
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE;

	DROP TEMPORARY TABLE IF EXISTS tmp.zone;
	CREATE TEMPORARY TABLE tmp.zone
		SELECT z.id 
			FROM zone z
				JOIN agencyMode am ON am.id = z.agencyModeFk
				JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
			WHERE dm.code IN ('AGENCY','DELIVERY'); 

	CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE);

	DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes;
	CREATE TEMPORARY TABLE tmp.zoneNodes (
			geoFk INT,
			name VARCHAR(100),
			parentFk INT,
			sons INT,
			isChecked BOOL DEFAULT 0,
			zoneFk INT,
			PRIMARY KEY zoneFkk (zoneFk, geoFk),
			INDEX(geoFk))
			ENGINE = MyISAM;
		
	OPEN cur1;
	cur1Loop: LOOP
		SET vIsDone = FALSE;
		FETCH cur1 INTO vZoneFk;
		IF vIsDone THEN
			LEAVE cur1Loop;
	    END IF;
	   
		CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE);

		myLoop: LOOP	
			SET vGeoFk = NULL;
			SELECT geoFk INTO vGeoFk 
				FROM tmp.zoneNodes zn
				WHERE NOT isChecked
				LIMIT 1;
			
			IF vGeoFk IS NULL THEN
				LEAVE myLoop;
			END IF;
		
			CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE);
			UPDATE tmp.zoneNodes
				SET isChecked = TRUE 
				WHERE geoFk = vGeoFk;
		END LOOP;

	END LOOP;
	CLOSE cur1;
	DELETE FROM tmp.zoneNodes 
		WHERE sons > 0;
	
	DROP TEMPORARY TABLE IF EXISTS geoCollision;
	CREATE TEMPORARY TABLE geoCollision
		SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk
			FROM tmp.zoneNodes zn
				JOIN zone z ON z.id = zn.zoneFk
				JOIN zoneWarehouse zw ON z.id = zw.zoneFk 
	        GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk
	        HAVING count(*) > 1;
	
	SELECT '<table  cellspacing="10">
				<tr>
					<th>C.Postal</th>
					<th>Número de zona</th>
					<th>Precio</th>
					<th>Zona</th>
					<th>Almacén</th>
					<th>Salix</th>
                 </tr>' INTO vTableCollisions;
                
    INSERT INTO mail (receiver,replyTo,subject,body)                
		SELECT 'pepe@verdnatura.es' receiver,
	           'noreply@verdnatura.es' replyTo,
	            CONCAT('Colisiones en zonas ', util.VN_CURDATE()) subject,
	            CONCAT(vTableCollisions,
	            	GROUP_CONCAT(sub.td SEPARATOR ''),
	            	'</table>') body
			FROM(SELECT 
					CONCAT('<tr>
						<td>', zn.name, '</td>
						<td>', zoneFk,'</td>
						<td>', z.price,'</td>
						<td>', z.name,'</td>
						<td>', w.name, '</td>
						<td>', CONCAT('<a href="https://salix.verdnatura.es/#!/zone/', 
								zoneFk,
								'/location?q=%7B%22search%22:%22',
								zn.name, 
								'%22%7D">'
								'https://salix.verdnatura.es/#!/zone/', 
								zoneFk,
								'/location?q=%7B%22search%22:%22',
								zn.name, 
								'%22%7D</a>'),'</td>
						</tr>') td
				FROM tmp.zoneNodes zn
					JOIN zone z ON z.id = zn.zoneFk
					JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk
					JOIN warehouse w ON w.id = gc.warehouseFk) sub;
			
	DROP TEMPORARY TABLE 
		geoCollision, 
		tmp.zone,
		tmp.zoneNodes;
END$$
DELIMITER ;
