<?php
class Calendarista_HolidayController extends Calendarista_BaseController{
	public function __construct($updateCallback){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_holiday')){
			return;
		}
		parent::__construct(null, $updateCallback);
	}
	public function update($callback){
		$projectId = isset($_POST['projectId']) ? intval($_POST['projectId']) : null;
		$applyAll = isset($_POST['apply_all']);
		$availabilityId = isset($_POST['availabilityId']) ? intval($_POST['availabilityId']) : null;
		$holidays = isset($_POST['holidays']) ? $_POST['holidays'] : array();
		$holidaysUndo = isset($_POST['holidays_undo']) ? array_map('intval', $_POST['holidays_undo']) : array();
		$availabilities = null;
		if($applyAll){
			$availabilityRepo = new Calendarista_AvailabilityRepository();
			$availabilityList = $availabilityRepo->readAllByService(array($projectId));
			foreach($availabilityList as $availability){
				if(!$availabilities){
					$availabilities = array();
				}
				array_push($availabilities, $availability->id);
			}
		}
		if(!$availabilities){
			$availabilities = array($availabilityId);
		}
		$repo = new Calendarista_HolidaysRepository();
		foreach($availabilities as $_availabilityId){
			if(count($holidays) > 0){
				foreach($holidays as $holiday){
					$_holiday = $repo->readByAvailabilityIdAndDate($_availabilityId, $holiday);
					if($_holiday){
						continue;
					}
					$result = $repo->insert(array(
						'projectId'=>$projectId
						, 'availabilityId'=>$_availabilityId
						, 'holiday'=>$holiday
					));
				}
			}
			if(($applyAll && count($holidaysUndo) > 0) && $availabilityId !== $_availabilityId){
				foreach($holidaysUndo as $holidayId){
					$_holiday = $repo->read($holidayId);
					if($_holiday){
						$repo->deleteByAvailabilityIdAndDate($_availabilityId, $_holiday['holiday']);
					}
				}
			}
		}
		if(count($holidaysUndo) > 0){
			foreach($holidaysUndo as $holidayId){
				$result = $repo->delete($holidayId);
			}
		}
		$this->executeCallback($callback, array($result));
	}
}
?>