<?php

class BillingContactService extends BillingService {
	
	protected static $instance = null;
	
	public function getCreateCustomerForm($storeId) {
		$responseContact = $this->executeGetContactParams($storeId);
		if ($responseContact->hasErrors()) {
			throw new BillingServiceException('Can not retrieve create customer form for Store with id "' . $storeId . '"');
		}
		$responseQuestion = $this->executeGetCustomQuestions($storeId);
		if ($responseQuestion->hasErrors()) {
			throw new BillingServiceException('Can not retrieve create customer custom questions form for Store with id "' . $storeId . '"');
		}
		$result = array_merge((array)$responseContact->getData(), (array)$responseQuestion->getData());
		return new BillingContactInformationForm($result);

	}
	
	public function collectCustomerForm($storeId, $values) {
		$responseContact = $this->executeCollectContactParams($storeId, $values);
		$responseQuestion = $this->executeCollectCustomQuestions($storeId, $values);
		$errors = array_merge((array)$responseContact->getErrors(), (array)$responseQuestion->getErrors());
		$violations = array_merge((array)$responseContact->getViolations(), (array)$responseQuestion->getViolations());
		$data = array_merge((array)$responseContact->getData(), (array)$responseQuestion->getData());
		return new CollectFormResult($errors, $violations, $data);
	}
	
	public function login($login, $password) {
		$response = $this->executeLogin($login, $password);
		if ($response->hasErrors()) {
			throw new BillingObjectException('Cannot log in as "' . $login . '"');
		} else {
			$customer = new BillingCustomer($response->getData());
			sfContext::getInstance()->getUser()->setAttribute('customer', $customer);
			$this->removeInvalidCoupons();
			return $customer;
		}
	}
	
	public function loginByShoppingSessionId($shoppingSessionId) {
		$response = $this->executeLoginBySSID($shoppingSessionId);
		if ($response->hasErrors()) {
			throw new BillingObjectException('Can not login by shopping session ID "' . $shoppingSessionId . '"');
		} else {
			$customer = new BillingCustomer($response->getData());
			sfContext::getInstance()->getUser()->setAttribute('customer', $customer);
			$this->removeInvalidCoupons();
			return $customer;
		}
	}
	
	private function removeInvalidCoupons() {
		$cart = ResourceLocator::getInstance()->cart;
		foreach ($cart->getPurchases() as $purchase) {
			if (($coupon = $purchase->getCoupon()) && $coupon->couponNewOnly) {
				$purchase->unsetCoupon();
			}
		}
		foreach ($cart->getAddons() as $addon) {
			if (($coupon = $addon->getCoupon()) && $coupon->couponNewOnly) {
				$addon->unsetCoupon();
			}
		}
	}

	public static function getInstance() {
		if (self::$instance == null) {
			self::$instance = new self(self::prepareSoapClient('contact'));
		}
		return self::$instance;
	}

}