<?php

require_once("lib-action/genericactions.php");

class AddBillingAccountResponse extends AddResponseAction
{
	public function __construct()
	{
		require_once("object_managers/CryptManager.php");
		CryptManager::setDefaultKey();

		global $CONF;
		$clientContactID = $CONF["user"]["clientContactID"];

		$_REQUEST["clientContactID"] = $clientContactID;

		loadConfigs("payment");
		if ($CONF["payment"]["clientSidePaymentOptions"][ getAPITypeName( "billingAccount", (int)$_REQUEST["billingAccountType"] ) ] != 1) {
			$this->addError(blmsg("TRANS_ACTIONERROR"), blmsg("TRANS_NO_ALLOWED_BILLING_TYPES_FOR_ADD"));
			$this->addErrorTemplates();
			exit;
		}

		$this->d = new DataSource("billingAccounts");
		$description = $this->d->getDescription();
		$description["names"]["file"] = "profile";
		parent::AddResponseAction();

		$success_validation = true;

		$billingAccountType = bgpc("billingAccountType");
		if($billingAccountType == getAPITypeID("billingAccount", "manual") || $billingAccountType == getAPITypeID("billingAccount", "secondary")) {
			unset($description["columns"]['billingBankType']);
			unset($description["columns"]['billingBankName']);
			unset($description["columns"]['billingBankState']);
			unset($description["columns"]['billingBankABACode']);
			unset($description["columns"]['billingBankAccountNum']);
			unset($description["columns"]['billingBankLicenseNum']);
			unset($description["columns"]['billingBankLicenseState']);
			unset($description["columns"]['billingBankDob']);

			unset($description["columns"]['billingCardNameOnCard']);
			unset($description["columns"]['billingCardType']);
			unset($description["columns"]['billingCardNum']);
			unset($description["columns"]['billingCardExpMonth']);
			unset($description["columns"]['billingCardExpYear']);
			unset($description["columns"]['billingCardIssueNum']);
			unset($description["columns"]['billingCardStartDate']);
		} else if($billingAccountType == getAPITypeID("billingAccount", "card")) {
			unset($description["columns"]['billingBankType']);
			unset($description["columns"]['billingBankName']);
			unset($description["columns"]['billingBankState']);
			unset($description["columns"]['billingBankABACode']);
			unset($description["columns"]['billingBankAccountNum']);
			unset($description["columns"]['billingBankLicenseNum']);
			unset($description["columns"]['billingBankLicenseState']);
			unset($description["columns"]['billingBankDob']);

			$billingCardType = (int) $_REQUEST["billingCardType"];
			$cardExtraTypes = getAPITypes("cardExtraIDs");
			if(!in_array($billingCardType, $cardExtraTypes)) {
				unset($description["columns"]['billingCardIssueNum']);
				unset($description["columns"]['billingCardStartDate']);
			}
		} else {
			unset($description["columns"]['billingCardNameOnCard']);
			unset($description["columns"]['billingCardType']);
			unset($description["columns"]['billingCardNum']);
			unset($description["columns"]['billingCardExpMonth']);
			unset($description["columns"]['billingCardExpYear']);
			unset($description["columns"]['billingCardIssueNum']);
			unset($description["columns"]['billingCardStartDate']);
		}

		$this->d->setDescription($description);
		switch ($billingAccountType)
		{
			case getAPITypeID("billingAccount", "card"):
				$validation_fields = array(
					"billingAccountType" => INPUT_RESTRICTION_UNSIGNED_INT,
					"billingCardNameOnCard" => INPUT_RESTRICTION_STRING|INPUT_RESTRICTION_REQUIRED,
					"billingCardExpMonth" => INPUT_RESTRICTION_MONTH|INPUT_RESTRICTION_REQUIRED,
					"billingCardExpYear" => INPUT_RESTRICTION_YEAR|INPUT_RESTRICTION_REQUIRED,
					"billingCardNum" => array(
						INPUT_RESTRICTION_INT|INPUT_RESTRICTION_REQUIRED|INPUT_RESTRICTION_MAXLEN|INPUT_RESTRICTION_MINLEN|INPUT_RESTRICTION_CARD,
						array(
							'maxLength' => 19,
							'minLength' => 13,
							'allowedCardTypes' => array(getAPITypeName("card", bgpc('billingCardType'))),
						),
					),
                );
				break;
			case getAPITypeID("billingAccount", "echeck"):
			case getAPITypeID("billingAccount", "bank"):
			case getAPITypeID("billingAccount", "wire"):
				$validation_fields = array(
					"billingAccountType" => INPUT_RESTRICTION_UNSIGNED_INT,
					"billingBankType" => INPUT_RESTRICTION_UNSIGNED_INT,
					"billingBankName" => INPUT_RESTRICTION_STRING|INPUT_RESTRICTION_REQUIRED,
					"billingBankState" => INPUT_RESTRICTION_STRING,
					"billingBankAbaCode" => INPUT_RESTRICTION_UNSIGNED_INT|INPUT_RESTRICTION_REQUIRED,
					"billingBankAccountNum" => INPUT_RESTRICTION_UNSIGNED_INT|INPUT_RESTRICTION_REQUIRED,
					"billingBankLicenseNum" => INPUT_RESTRICTION_STRING,
					"billingBankLicenseState" => INPUT_RESTRICTION_STRING,
                );
				break;
			case getAPITypeID("billingAccount", "hspcbanktransfer"):
				require_once("ModuleTool.php");
				$gateway_id = bgpc("selected_ddbp_gateway_id");
				$plugin = ModuleTool::getModuleInstance("gateway", "HSPCBankTransfer", array("gateway_id" => $gateway_id));
				$billing_account = Factory()->ClientBillingAccount();
				// check vendors of client and payment gateway
				$customer = Factory()->ClientContact(getCurrentSession()->user_id)->Client;
				if (!$customer->hasSameVendor(Factory()->PaymentGateway($gateway_id))) {
					throw new ForbiddenOperationException();
				}
				$billing_account->payment_gateway_id = $gateway_id;
				$adapter = $plugin->getPaymentMethodAdapter($billing_account);
				$adapter->collectInputFields("_{$gateway_id}");
				$adapter_input_fields = $adapter->getInputFields();
				$validation_fields = array(
					"billingAccountType" => INPUT_RESTRICTION_UNSIGNED_INT
				);
				foreach (array_keys($adapter_input_fields) as $field_name) {
					$validation_fields["{$field_name}_{$gateway_id}"] = INPUT_RESTRICTION_STRING|INPUT_RESTRICTION_REQUIRED;
				}
				$adapter_validation = $adapter->validate();
				if (HSPC_PM_Adapter::VALIDATION_OK != $adapter_validation) {
					$success_validation = false;
					billing_put_error($adapter_validation);
				}
				break;
		}
		$this->setReferralActionID(getActionID("AddBillingAccount"));
		$this->setReferralActionFile("profile.php");
		$args = array("billingAccountID" => bgpc("billingAccountID"), "billingAccountType" => $billingAccountType, "selected_ddbp_gateway_id" => $gateway_id);
		$success_validation = $this->validateMultiInputs( $validation_fields, array(), array(), 1, $args ) && $success_validation;
		if (! $success_validation) {
			$this->validationRedirect($args, array(), true); //Force redirect
			exit;
		}
	}

	public function addResponseHandler()
	{
		global $CONF;
		$billingAccountID = $this->lastInsertID;

		$contact = oneByID(":contacts", $CONF["user"]["clientContactID"]);
		if ((int)$contact['contactPrimary'] && (int)$_REQUEST['defaultBillingAccount']){
			updateForKey(":clientsGeneric", $CONF['user']['id'], array(
				"defaultBillingAccountID" => $billingAccountID,
			));
		}

		if (bgpc("billingAccountType") == ClientBillingAccount::TYPE_HSPC_BANK_TRANSFER) {
			require_once("ModuleTool.php");
			$gateway_id = bgpc("selected_ddbp_gateway_id");
			$plugin = ModuleTool::getModuleInstance("gateway", "HSPCBankTransfer", array("gateway_id" => $gateway_id));

			$billing_account = Factory()->ClientBillingAccount($billingAccountID);
			$billing_account->payment_gateway_id = $gateway_id;
			$billing_account->client_contact_id = getCurrentSession()->user_id;
			$billing_account->billing_account_type = bgpc("billingAccountType");

			$adapter = $plugin->getPaymentMethodAdapter($billing_account);
			$adapter->collectInputFields("_{$gateway_id}");
			$adapter->save();
		}

		foreach((array) $_REQUEST["packages"] as $packageID) {
			$q = new MBQuery(
				"SetBillingAccountShare", "insert",
				array(
					"billingAccountID" => $billingAccountID,
					"billingAccountShareGroup" => "0",
					"billingAccountFallbackGroup" => "1",
					"billingAccountShareValue" => "1",
					"packageID" => (int) $packageID,
				)
			);
			$r =& $q->getResult();
			if(!$r->getSuccess()) {
				$this->addErrorsFromResult($r);
				return false;
			}
		}
		return true;
	}

	public function overrideValidateColumnParamType($column, $columnType, $mode, $paramType, $isRequired)
	{
		switch($column) {
			case "billingCardNum":
				$paramType |= INPUT_RESTRICTION_MAXLEN|INPUT_RESTRICTION_MINLEN|INPUT_RESTRICTION_CARD;
				$args = array(
					'maxLength' => 19,
					'minLength' => 13,
					'allowedCardTypes' => array(getAPITypeName("card", $_REQUEST['billingCardType'])),
				);
				break;
			case "billingBankAccountNum":
				if(empty($_REQUEST["billingBankAccountNum"])) {
					$columnType = 0;
					break;
				}
				break;
			default:
				$args = array();
				break;
		}

		return array($paramType, $isRequired, $args);
	}
}
