<?php

class BillingDomainPlan extends BillingPlan {
	
	const PURCHASE_TYPE_REGISTER = 'register';
	
	const PURCHASE_TYPE_TRANSFER = 'transfer';
	
	private $_domains = array();
	
	public function getDomains($storeId) {
		if (!isset($this->_domains[$storeId])) {
			$this->_domains[$storeId] = ResourceLocator::getInstance()->billingDomainService->getDomains($this->getId(), $storeId);
		}
		return $this->_domains[$storeId];
	}
	
	public function hasDomains($storeId) {
		return $this->getDomains($storeId) ? true : false;
	}
	
	public function getLowestCyclePrice($storeId, $currencyId) {
		$allowedTLDs = array();
		foreach($this->getDomains($storeId) as $domain) {
			$allowedTLDs[$domain->tldID] = $domain;
		}
		$amount = false;
		$result = null;
		foreach ($this->getVariants() as $variant) {
			if (!isset($allowedTLDs[$variant->tldID])) {
				continue;
			}
			foreach ($variant->getPricesByCurrency($currencyId) as $price) {
				if ($price->hasCycleFee() && (!$amount || $price->getCycleFee() < $amount)) {
					$amount = $price->getCycleFee();
					$result = $price;
				}
			}
		}
		return $result;
	}
	
	public function getLowestTransferPrice($storeId, $currencyId) {
		$allowedTLDs = array();
		foreach($this->getDomains($storeId) as $domain) {
			$allowedTLDs[$domain->tldID] = $domain;
		}
		$amount = false;
		$result = null;
		foreach ($this->getVariants() as $variant) {
			if (!isset($allowedTLDs[$variant->tldID])) {
				continue;
			}
			foreach ($variant->getPricesByCurrency($currencyId) as $price) {
				if ($price->hasTransferFee() && (!$amount || $price->getTransferFee() < $amount)) {
					$amount = $price->getTransferFee();
					$result = $price;
				}
			}
		}
		return $result;
	}
	
	public function hasTransferPrice($currencyId) {
		foreach ($this->getVariants() as $variant) {
			foreach ($variant->getPricesByCurrency($currencyId) as $price) {
				if ($price->hasTransferFee()) {
					return true;
				}
			}
		}
		return false;
	}
	
	public function mayHaveDomains() {
		return false;
	}
	
	public function mustHaveDomains() {
		return false;
	}

	public function getTLDsForCatalog($storeID) {
		$TLDSsDisplayConfig = sfConfig::get('mod_catalog_plan_tlds');

		$allTLDs = array();
		foreach($this->getDomains($storeID) as $domain) {
			$allTLDs[] = $domain->tldExtension;
		}
		
		$planTLDs = array();
		if(!empty($TLDSsDisplayConfig['filterTLDs'])) {
			foreach($TLDSsDisplayConfig['filterTLDs'] as $TLD) {
				if(in_array($TLD, $allTLDs)) {
					$planTLDs[] = $TLD;
				}
			}
		} else {
			$displayedTLDs = 0;
			foreach($allTLDs as $TLD) {
				if($displayedTLDs == $TLDSsDisplayConfig['maxDisplayCount']) {
					break;
				}
				$planTLDs[] = $TLD;
				$displayedTLDs++;
			}
		}

		return $planTLDs;
	}
}