<?php
class Calendarista_DynamicFieldController extends Calendarista_BaseController{
	private $repo;
	private $availability;
	public function __construct($createCallback, $updateCallback, $deleteCallback){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'dynamic_field')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$this->repo = new Calendarista_DynamicFieldRepository();
		parent::__construct($createCallback, $updateCallback, $deleteCallback);
	}
	public function create($callback){
		$projectId = (int)$this->getPostValue('projectId');
		$availabilityId = (int)$this->getPostValue('availabilityId');
		$cost = $this->getPostValue('cost');
		$min = (int)$this->getPostValue('min_0');
		$max = (int)$this->getPostValue('max_0');
		$label = $this->getPostValue('label');
		$byOptional = 0;
		$limitBySeat = 0;
		$required = 0;
		$fixedCost = 0;
		if(isset($_POST['byOptional'])){
			$byOptional = 1;
		}
		if(isset($_POST['limitBySeat'])){
			$limitBySeat = 1;
		}
		if(isset($_POST['required'])){
			$required = 1;
		}
		if(isset($_POST['fixedCost'])){
			$fixedCost = 1;
		}
		$df = new Calendarista_DynamicField(array(
			'projectId'=>$projectId
			, 'availabilityId'=>$availabilityId
			, 'label'=>$label
			, 'byOptional'=>$byOptional
			, 'limitBySeat'=>$limitBySeat
			, 'cost'=>$cost ? (float)$cost : null
			, 'required'=>(int)$required
			, 'data'=>array(array('min'=>$min, 'max'=>$max))
			, 'fixedCost'=>(int)$fixedCost
		));
		$newId = $this->repo->insert($df);
		$this->executeCallback($callback, array($newId));
	}
	public function update($callback){
		$id = (int)$this->getPostValue('calendarista_update');
		$label = $this->getPostValue('label');
		$byOptional = 0;
		$limitBySeat = 0;
		$required = 0;
		$fixedCost = 0;
		if(isset($_POST['byOptional'])){
			$byOptional = 1;
		}
		if(isset($_POST['limitBySeat'])){
			$limitBySeat = 1;
		}
		if(isset($_POST['required'])){
			$required = 1;
		}
		if(isset($_POST['fixedCost'])){
			$fixedCost = 1;
		}
		$cost = $this->getPostValue('cost');
		$min = (int)$this->getPostValue('min_0');
		$max = (int)$this->getPostValue('max_0');
		$dynamicField = $this->repo->read($id);
		$dynamicField->label = $label;
		$dynamicField->byOptional = $byOptional;
		$dynamicField->limitBySeat = $limitBySeat;
		$dynamicField->cost = $cost ? (float)$cost : null;
		$dynamicField->required = (int)$required;
		$dynamicField->data = array(array('min'=>$min, 'max'=>$max));
		$dynamicField->fixedCost = (int)$fixedCost;
		$this->repo->update($dynamicField);
		$this->executeCallback($callback, array($id));
	}
	public function delete($callback){
		$id = (int)$this->getPostValue('calendarista_delete');
		$this->repo->delete($id);
		$this->executeCallback($callback, array());
	}
}
?>