<?php

class PurchaseManager {

	public static function preparePurchaseData($store, $purchase, $subPurchases = array(), &$amount, &$totalAmount, &$prorationAmount, &$minimalCycle) {
		$subData = $ownDomains = array();

		$plan = ResourceLocator::getInstance()->billingPlanService->getById(
			$purchase->getPlanId(),
			$store->getId(),
			$purchase->hasCoupon() ? $purchase->getCoupon()->getId() : false
		);
		foreach($purchase->getOwnDomains() as $domainName => $domainData) {

			$fakeId = ResourceLocator::getInstance()->cart->generateFakeId();
			$ownDomains[$fakeId][$domainName] = array(
				'id' => $fakeId,
				'type' => __('TRANS_YOUR_OWN_DOMAIN'),
				'name' => $domainName,
				'price' => null,
				'cycle' => null,
				'hasAddAddonAbility' => false,
				'hasAddDomainAbility' => false,
				'fake' => true,
				'purchases' => array()
			);
		}

		foreach ($subPurchases as $subPurchase) {
			$subData[$subPurchase->getId()] = self::preparePurchaseData($store, $subPurchase, array(), $amount, $totalAmount, $prorationAmount, $minimalCycle);
		}

		$useTransferFee = $plan instanceof BillingDomainPlan && $purchase->getParameter('type') == BillingDomainPlan::PURCHASE_TYPE_TRANSFER ? true : false;

		$price = $plan->getPriceById($purchase->getPriceId());
		$cycle = $plan->getCycle($price->cycleID);
		if (!$minimalCycle || $minimalCycle->getLength() < $cycle->getLength()) {
			$minimalCycle = $cycle;
		}
		$amount += $price->getTotalFee(true, false, $useTransferFee);
		$totalAmount += $price->getTotalFee(true, true, $useTransferFee);
		$prorationAmount += $price->hasProrationFee() ? $price->getProrationFee() : $price->getTotalFee(true, true, $useTransferFee);

		$hasAddAddonAbility = $plan->mayHaveAddons() && $plan->hasAddAddonAvailability($cycle->cycleID);

		$hasAddDomainAbility = false;
		if ($plan->mayHaveDomains()) {
			if ($store->hasAbilityToUseOwnDomain()) {
				$hasAddDomainAbility = true;
			} else {
				$domainPlan = $plan instanceof BillingDomainPlan ? $plan : $store->getDefaultDomainPlan();
				if ($domainPlan && $store->hasAbilityToPurchaseDomainPlan($domainPlan)) {
					$hasAddDomainAbility = true;
				}
			}
		}

		$data = array(
			'id' => $purchase->getId(),
			'type' => __('TRANS_PRODUCT_TYPE_NAME_' . $plan->productType),
			'name' => $purchase->getName(),
			'price' => $price,
			'cycle' => $cycle,
			'hasAddAddonAbility' => $hasAddAddonAbility,
			'hasAddDomainAbility' => $hasAddDomainAbility,
			'useTransferFee' => $useTransferFee,
			'fake' => false,
			'purchases' => $subData,
			'ownDomains' => $ownDomains,
		);
		return $data;
	}

	public static function prepareAddonData($store, $addon, &$amount, &$totalAmount, &$prorationAmount, &$minimalCycle) {

		$billingAddon = ResourceLocator::getInstance()->billingAddonService->getById(
			$addon->getAddonId(),
			$addon->getPlanId(),
			$store->getId(),
			$addon->getCycleId(),
			$addon->hasCoupon() ? $addon->getCoupon()->getId() : false
		);

		$price = $billingAddon->getPrice();
		$cycle = $billingAddon->getCycle($price->cycleID);
		if (!$minimalCycle || $minimalCycle->getLength() < $cycle->getLength()) {
			$minimalCycle = $cycle;
		}
		$amount += $price->getTotalFee(true, false);
		$totalAmount += $price->getTotalFee();
		$prorationAmount += $price->hasProrationFee() ? $price->getProrationFee() : $price->getTotalFee(true, true, $useTransferFee);

		return array(
			'id' => $addon->getId(),
			'name' => $billingAddon->productName,
			'price' => $price,
			'cycle' => $cycle
		);
	}

	public static function purchaseDomains($request, $store, $cart, $plan, &$duplicatedDomains = array()) {
		
		$SLD = $request->getParameter('SLD');
		
		$registerTLDs = $request->getParameter('registerTLDs', array());
		$transferTLDs = $request->getParameter('transferTLDs', array());
		
		$alreadyPurchasedDomains = array();
		$domainPurchases = $cart->getDomainPurchases();
		foreach ($domainPurchases as $purchase) {
			$data = $purchase->getParameter('domainData');
			$alreadyPurchasedDomains[] = $data['name'];
		}
		
		$currentlyPurchasingDomains = array();
		if ($currentCartItem = $cart->getCurrentItem()) {
			foreach ($currentCartItem->getPurchases(true) as $purchase) {
				if ($purchase->getType() == BillingPlan::TYPE_DOMAIN) {
					$data = $purchase->getParameter('domainData');
					$currentlyPurchasingDomains[] = $data['name'];
				} else {
					if ($data = $purchase->getParameter('domainData')) {
						$alreadyPurchasedDomains[] = $data['name'];
					}
				}
			}
		}
		
		$count = 0;
		
		$purchases = array();
		foreach ($registerTLDs as $TLD) {
			$domainName = $SLD . '.' . $TLD;
			if (array_search($domainName, $alreadyPurchasedDomains) !== false) {
				$duplicatedDomains[] = $domainName;
				continue;
			}
			if (array_search($domainName, $currentlyPurchasingDomains) !== false) {
				$count++;
				continue;
			}
			$priceId = $request->getParameter('price_' . str_replace(".", "_", $TLD));
			$cycleId = $plan->getPriceById($priceId)->cycleID;
			
			$purchase = self::prepareDomainPurchase($plan->getId(), $cycleId, $priceId, BillingDomainPlan::PURCHASE_TYPE_REGISTER, $SLD, $TLD);
			if ($coupon = $plan->getPreappliedCoupon()) {
				$purchase->setCoupon($coupon);
			}
			
			$purchases[] = $purchase;
			$count++;
		}
		
		foreach ($transferTLDs as $TLD) {
			$domainName = $SLD . '.' . $TLD;
			if (array_search($domainName, $alreadyPurchasedDomains) !== false) {
				$duplicatedDomains[] = $domainName;
				continue;
			}
			if (array_search($domainName, $currentlyPurchasingDomains) !== false) {
				$count++;
				continue;
			}
			$priceId = $request->getParameter('price_' . str_replace(".", "_", $TLD));
			$cycleId = $plan->getPriceById($priceId)->cycleID;
			
			$purchase = self::prepareDomainPurchase($plan->getId(), $cycleId, $priceId, BillingDomainPlan::PURCHASE_TYPE_TRANSFER, $SLD, $TLD);
			if ($coupon = $plan->getPreappliedCoupon()) {
				$purchase->setCoupon($coupon);
			}
			
			$purchases[] = $purchase;
			$count++;
		}
		
		if ($count && !$duplicatedDomains) {
			$cartItem = $cart->getCurrentItem();
			foreach ($purchases as $purchase) {
				$cartItem->addPurchase($purchase);
			}
			return true;
		} else {
			return false;
		}
		
	}
	
	private static function prepareDomainPurchase($planId, $cycleId, $priceId, $type, $SLD, $TLD) {
		$domainName = $SLD . '.' . $TLD;
		$purchase = new Purchase($planId, $cycleId, $priceId, $domainName, BillingPlan::TYPE_DOMAIN);
		$purchase->addParameter('type', $type);
		$domainData = array(
			'SLD' => $SLD,
			'TLD' => $TLD,
			'name' => $domainName
		);
		$purchase->addParameter('domainData', $domainData);
		return $purchase;
	}
}