<?php

/**
 * Description of Member
 *
 * @author Arkadiusz Rychlik <a.rychlik at eppe.com.pl>
 * @author Janusz
 */
class Newsletter_CRUD_Member extends Rtn_CRUD {

	protected $beanName = 'nlgroup';

	/**
	 * @param type $nlgroupId
	 * @param type $nluId
	 * @return type
	 */
	public function toggleActive() {
		$nlgroupId = func_get_arg(0);
		$nluId = func_get_arg(1);

		$reasons = [];

		if (!$this->_memberActive($nlgroupId, $nluId)) {
			if ($this->_canBeActivated($nlgroupId, $nluId)) {
				$result = $this->_activateMember($nlgroupId, $nluId);
			}
			else {
				$result = false;
				$reasons[] = __('Użytkownik nie posiada poprawnie zdefiniowanego adresu e-mail.');
			}
		}
		else {
			$result = $this->_deactivateMember($nlgroupId, $nluId);
		}

		return array('result' => $result, 'msg' => join('<br />', $reasons));
	}

	/**
	 * Czy jest członkiem grupy
	 * @param type $nlgroupId
	 * @param type $nluId
	 * @return type
	 */
	protected function _memberActive($nlgroupId, $nluId) {
		return R::getAll("SELECT * FROM nlgroupassign WHERE nluser_id = $nluId AND nlgroup_id = $nlgroupId");
	}

	protected function _activateMember($nlgroupId, $nluId) {
		return R::exec("INSERT INTO nlgroupassign (nluser_id,nlgroup_id) VALUES($nluId,$nlgroupId)");
	}

	protected function _deactivateMember($nlgroupId, $nluId) {
		return R::exec("DELETE FROM nlgroupassign WHERE nluser_id=$nluId AND nlgroup_id=$nlgroupId");
	}

	protected function _canBeActivated($nlgroupId, $nluId) {
		$bean = R::findOne('nluser', 'id = ?', [$nluId]);
		$email = $bean->email;
		$validator = new Zend_Validate_EmailAddress();
		return $validator->isValid($email);
	}

}
