<?php
class Calendarista_DynamicFieldPricingController extends Calendarista_BaseController{
	private $repo;
	public function __construct($createCallback, $updateCallback, $deleteCallback){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'dynamic_field_pricing')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$this->repo = new Calendarista_DynamicFieldPricingRepository();
		parent::__construct($createCallback, $updateCallback, $deleteCallback);
	}
	public function create($callback){
		$dynamicFieldId = (int)$this->getPostValue('dynamicFieldId');
		$cost = (float)$this->getPostValue('cost_');
		$fieldValue = (int)$this->getPostValue('fieldValue_');
		$duplicate = true;
		$result = $this->repo->checkDuplicate($dynamicFieldId, $fieldValue);
		$newId = null;
		if(!$result || count($result) === 0){
			$duplicate = false;
			$newId = $this->repo->insert(array(
				'dynamicFieldId'=>$dynamicFieldId
				, 'cost'=>$cost
				, 'fieldValue'=>$fieldValue
			));
		}
		$this->executeCallback($callback, array($newId, $duplicate));
	}
	public function update($callback){
		$id = (int)$this->getPostValue('calendarista_update');
		$dynamicFieldId = (int)$this->getPostValue('dynamicFieldId');
		$fieldValue = (int)$this->getPostValue('fieldValue_' . $id);
		$cost = (float)$this->getPostValue('cost_' . $id);
		$duplicate = false;
		$result = $this->repo->checkDuplicate($dynamicFieldId, $fieldValue);
		if($result){
			foreach($result as $r){
				if($r['id'] !== $id){
					$duplicate = true;
					break;
				}
			}
		}
		if(!$duplicate){
			$this->repo->update(array('id'=>$id, 'cost'=>$cost, 'fieldValue'=>$fieldValue));
		}
		$this->executeCallback($callback, array($id, $duplicate));
	}
	public function delete($callback){
		$val = isset($_POST['priceFields']) ? (array)$_POST['priceFields'] : null;
		if($val){
			$dynamicFieldPrices =  array_map('intval', $val);
			if(count($dynamicFieldPrices) === 0){
				$dynamicFieldPrices = array((int)$this->getPostValue('calendarista_delete'));
			}
			for($i = 0; $i < count($dynamicFieldPrices); $i++){
				$this->repo->delete($dynamicFieldPrices[$i]);
			}
		}
		$this->executeCallback($callback, array());
	}
}
?>