<?php

class BillingStore extends BillingObject implements BillingPlansContainer {
	
	private $_defaultDomainPlan = null;
	
	public function getPlan($id, $anonymously = false) {
		$plans = ResourceLocator::getInstance()->billingPlanService->getByStore($this->getId(), array($id), $anonymously);
		if (empty($plans)) {
			throw new BillingObjectException('Plan with id "' . $id . '" not found');
		}
		return array_shift($plans);
	}
	
	public function getPlans($anonymously = false) {
		return ResourceLocator::getInstance()->billingPlanService->getByStore($this->getId(), array(), $anonymously);
	}
	
	public function getAddons($cycleId, $anonymously = false) {
		$plans = $this->getPlans($anonymously);
		$addons = array();
		foreach ($plans as $plan) {
			foreach ($plan->getAddons($this->getId(), $cycleId, $anonymously) as $addon) {
				$addons[$addon->getId()] = $addon;
			}
		}
		return $addons;
	}
	
	public function getDefaultDomainPlan($anonymously = false) {
		if ($this->_defaultDomainPlan === null) {
			$plans = $this->getPlans($anonymously);
			$this->_defaultDomainPlan = false;
			foreach ($plans as $plan) {
				if ($plan->productType == BillingPlan::TYPE_DOMAIN) {
					$this->_defaultDomainPlan = $plan;
					break;
				}
			}
		}
		return $this->_defaultDomainPlan ? $this->_defaultDomainPlan : null;
	}
	
	public function hasAbilityToUseOwnDomain() {
		return in_array('dom_existing', $this->domainOptions);
	}
	
	public function hasAbilityToPurchasePlan(BillingPlan $plan) {
		$result = true;
		// check prices
		if (!$plan->hasPrices($this->currencyID)) {
			$result = false;
		}
		// check addons
		if ($plan->mustHaveAddons()) {
			$result = false;
			foreach ($plan->getPricesByCurrency($this->currencyID) as $price) {
				if ($plan->hasAddAddonAvailability($price->cycleID)) {
					$result = true;
					break;
				}
			}
		}
		// check domains
		if ($result) {
			if ($plan instanceof BillingDomainPlan) {
				$result = $this->hasAbilityToPurchaseDomainPlan($plan);
			} else {
				$allowUseOwn = $this->hasAbilityToUseOwnDomain();
				if ($plan->mustHaveDomains() && !$allowUseOwn) {
					if ($defaultDomainPlan = $this->getDefaultDomainPlan()) {
						$result = $this->hasAbilityToPurchaseDomainPlan($defaultDomainPlan);
					} else {
						$result = false;
					}
				}
				
			}
		}
		return $result;
	}
	
	public function hasAbilityToPurchaseDomainPlan(BillingDomainPlan $plan) {
		$allowRegister = in_array('dom_reg', $this->domainOptions);
		$allowTransfer = in_array('dom_transfer', $this->domainOptions);
		return ($allowRegister && $plan->hasPrices($this->currencyID) && $plan->hasDomains($this->getId())) || ($allowTransfer && $plan->hasTransferPrice($this->currencyID) && $plan->hasDomains($this->getId())) ? true : false;
	}
	
	protected function _extractId() {
		return $this->orderFormID;
	}
	
}