
DROP PROCEDURE IF EXISTS `vn`.`zone_getEvents`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getEvents`(
    vAgencyModeFk INT,
	vProvinceFk INT,
    vPostCode VARCHAR(255))
BEGIN
/**
 * Returns available events for the passed province/postcode and agency.
 *
 * @param vAgencyModeFk The agency mode id
 * @param vProvinceFk The province id
 * @param vPostCode The postcode or %NULL to use the province
 */
 	DECLARE vGeoFk INT;
    
    IF vPostCode IS NOT NULL THEN
		SELECT p.geoFk INTO vGeoFk
			FROM postCode p
				JOIN town t ON t.id = p.townFk
			WHERE p.`code` = vPostCode
				AND t.provinceFk = vProvinceFk;
	ELSE
		SELECT geoFk INTO vGeoFk
			FROM province
            WHERE id = vProvinceFk;
    END IF;

    CALL zone_getFromGeo(vGeoFk);
    
    DELETE t FROM tmp.zone t
		JOIN zone z ON z.id = t.id
        WHERE z.agencyModeFk != vAgencyModeFk;
	
    SELECT e.`from`, e.`to`, e.weekDays
		FROM tmp.zone t
			JOIN zoneEvent e ON e.zoneFk = t.id;
    
    SELECT DISTINCT e.`day`
		FROM tmp.zone t
			JOIN zoneExclusion e ON e.zoneFk = t.id;

	DROP TEMPORARY TABLE tmp.zone;
END$$
DELIMITER ;

