DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`zone_getEvents`(
	vGeoFk INT,
    vAgencyModeFk INT)
BEGIN
/**
 * Returns available events for the passed province/postcode and agency.
 *
 * @param vGeoFk The geo id
 * @param vAgencyModeFk The agency mode id
 */
	DECLARE vDeliveryMethodFk VARCHAR(255);

	DROP TEMPORARY TABLE IF EXISTS tZone;
	CREATE TEMPORARY TABLE tZone
		(id INT PRIMARY KEY)
		ENGINE = MEMORY;

	SELECT dm.`code` INTO vDeliveryMethodFk
		FROM agencyMode am
			JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
        WHERE am.id = vAgencyModeFk;

	IF vDeliveryMethodFk = 'PICKUP' THEN
		INSERT INTO tZone
			SELECT id
				FROM zone
                WHERE agencyModeFk = vAgencyModeFk;
	ELSE
		CALL zone_getFromGeo(vGeoFk);

		IF vAgencyModeFk IS NOT NULL THEN
			INSERT INTO tZone
				SELECT t.id
					FROM tmp.zone t
						JOIN zone z ON z.id = t.id
					WHERE z.agencyModeFk = vAgencyModeFk;
		ELSE
			INSERT INTO tZone
				SELECT t.id
					FROM tmp.zone t
						JOIN zone z ON z.id = t.id
						JOIN agencyMode am  ON am.id = z.agencyModeFk
						JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
				WHERE dm.`code` IN ('AGENCY', 'DELIVERY');
		END IF;
		DROP TEMPORARY TABLE tmp.zone;
	END IF;

	SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays
		FROM tZone t
			JOIN zoneEvent e ON e.zoneFk = t.id;

	SELECT e.zoneFk, e.dated
		FROM tZone t
			JOIN zoneExclusion e ON e.zoneFk = t.id
			LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id
			LEFT JOIN zoneGeo zg1 ON zg1.id = eg.geoFk
			JOIN zoneGeo zg2 ON zg2.id = vGeoFk
		WHERE eg.zoneExclusionFk IS NULL OR zg2.`path` LIKE CONCAT(zg1.`path`,'%');

	DROP TEMPORARY TABLE tZone;
END$$
DELIMITER ;