<?php
class Calendarista_MapController extends Calendarista_BaseController{
	public function __construct($updateCallback){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'map')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		parent::__construct(null, $updateCallback, null);
	}
	public static function redirect(){
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		//if we want to redirect then we need to do it early in the wordpress life cycle
		//the Redirect controller is going to call us through this method.
		if (array_key_exists('calendarista_create', $_POST)){
			self::createMap();
		}else if(array_key_exists('calendarista_delete', $_POST)){
			self::deleteMap();
		}
	}
	public static function createMap(){
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$repo = new Calendarista_MapRepository();
		$map = new Calendarista_Map($_POST);
		$result = $repo->insert($map);
		$url = admin_url() . 'admin.php?page=calendarista-places&calendarista-tab=1&newmapservice=true&projectId=' . $map->projectId;
		if (wp_redirect($url)) {
			exit;
		}
	}
	public function update($callback){
		$repo = new Calendarista_MapRepository();
		$map = new Calendarista_Map($_POST);
		if(array_key_exists('tabName', $_POST) && $_POST['tabName'] === 'destination_settings'){
			$map->enableDestinationField = isset($_POST['enableDestinationField']);
		}
		$result = $repo->update($map);
		$this->executeCallback($callback, array($map, $result));
	}
	public static function deleteMap(){
		$maps = array_map('intval', isset($_POST['id']) ? $_POST['id'] : '');
		$mapRepo = new Calendarista_MapRepository();
		$aggregateRepo = new Calendarista_PlaceAggregateCostRepository();
		foreach($maps as $mapId){
			$aggregateRepo->deleteAll($mapId);
			$result = $mapRepo->delete($mapId);
		}
		$url = admin_url() . 'admin.php?page=calendarista-places';
		if (wp_redirect($url)) {
			exit;
		}
	}
}
?>