<?php
class Calendarista_StaffController extends Calendarista_BaseController{
	private $staffRepository;
	public function __construct($createCallback, $updateCallback, $deleteCallback){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_staff')){
			return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		$this->staffRepository = new Calendarista_StaffRepository();
		parent::__construct($createCallback, $updateCallback, $deleteCallback);
	}
	public function create($callback){
		$projectId = (int)$this->getPostValue('projectId');
		$availabilityId = (int)$this->getPostValue('availabilityId');
		$name = trim($this->getPostValue('name'));
		$email = trim($this->getPostValue('email'));
		$userId = Calendarista_PermissionHelper::userExistsByEmail($email);
		$result = false;
		if($userId !== false && !$this->staffMemberExists($userId, $availabilityId)){
			$project = Calendarista_ProjectHelper::getProject($projectId);
			$availabilityRepo = new Calendarista_AvailabilityRepository();
			$availability = $availabilityRepo->read($availabilityId);
			$this->staffRepository->insert(array(
				'projectId'=>$projectId
				, 'availabilityId'=>$availabilityId
				, 'projectName'=>$project->name
				, 'availabilityName'=>$availability->name
				, 'name'=>$name
				, 'email'=>$email
				, 'userId'=>$userId
			));
			$result = true;
		}
		$this->executeCallback($callback, array($result, $email));
	}
	
	public function update($callback){
		$id = (int)$this->getPostValue('id');
		$name = trim($this->getPostValue('name'));
		$email = trim($this->getPostValue('email'));
		$userId = Calendarista_PermissionHelper::userExistsByEmail($email);
		$result = false;
		if($userId !== false){
			$this->staffRepository->update(array(
				'id'=>$id
				, 'name'=>$name
				, 'email'=>$email
				, 'userId'=>$userId
			));
			$result = true;
		}
		$this->executeCallback($callback, array($result, $email));
	}
	protected function staffMemberExists($userId, $availabilityId){
		$repo = new Calendarista_StaffRepository();
		$result = $repo->readAll(array('userId'=>$userId, 'availabilityId'=>$availabilityId));
		if($result !== false && $result['total'] > 0){
			return true;
		}
		return false;
	}
	public function delete($callback){
		$id = (int)$this->getPostValue('id');
		$result = $this->staffRepository->delete($id);
		$this->executeCallback($callback, array($id, $result));
	}
}
?>