<?php
require_once("lib-action/action.php");

class EditBillingAccount extends MB_Action
{
	public $params = array("clientID", "clientContactID", "billingAccountID");

	public function execute()
	{
		parent::execute();

		$clientID = getParam('clientID');
		$clientContactID = getParam('clientContactID');
		$billingAccountID = getParam('billingAccountID');
		if (!$clientContactID && $billingAccountID){
			$clientContactID = Factory()->ClientBillingAccount($billingAccountID)->client_contact_id;
		}
		if (!$clientID && $clientContactID){
			$clientID = Factory()->ClientContact($clientContactID)->client_id;
		}

		if(!$billingAccountID) {
			$this->addError(TRANS_ACTIONERROR, "No billing account ID given.");
		} else if(!$clientContactID) {
			$this->addError(TRANS_ACTIONERROR, "No client contact ID given.");
		} else if(!$clientID) {
			$this->addError(TRANS_ACTIONERROR, "No client ID given.");
		} else {

			require_once("object_managers/ClientBillingAccountManager.php");
			ClientBillingAccountManager::repairAccount(Factory()->ClientBillingAccount($billingAccountID));

			require_once("object_managers/CryptManager.php");
			$decParams = array();
			if ( 1 == bgpc("showDecryptedCC") ) {
				try {
					switch ( CryptManager::getEncryptionMode() ) {
					case CryptManager::MODE_LEK:
						CryptManager::checkEncryptionKey($lekPin = bgpc("lekPin"), getCurrentSession()->user_id);
						$decParams = array("getDecryptedCC" => 1, "lekPin" => $lekPin);
						CryptManager::setKey($lekPin);
						break;
					case CryptManager::MODE_PASSPHRASE:
						if ("" != ($passphrase = bgpc("passphrase"))) {
							CryptManager::checkEncryptionKey($passphrase, getCurrentSession()->user_id);
						}
						$decParams = array("getDecryptedCC" => 1, "passphrase" => $passphrase);
						CryptManager::setKey($passphrase);
						break;
					}
				} catch(ProductException $e) {
					billing_put_error($e->getMessage());
				}
			}
			$query = $this->getMBAPIQuery("GetClients", "", array("getContactData"=>"4", "getBillingData"=>"4", "clientContactID" =>$clientContactID) + $decParams);
			$data = dispatchMBAPI($query, 1);

			$results =& $data["mbapi"][0]["results"][0];

			if ($this->addMBAPIErrors($data) === 0 && !$this->getNumErrors())
			{
				$client = Factory()->Client($clientID);

				require_once("object_managers/SecurityManager.php");
				SecurityManager::pushCurrentActionIntoLog(
					SecurityManager::USER_TYPE_CLIENT,
					$clientID,
					$client->PrimaryContact->contact_username,
					"TRANS_ACTION_LOG_REASON_SHOW_BILLING_ACCOUNT_DETAILS",
					blmsg(
						(1 == bgpc("showDecryptedCC") ? "TRANS_ACTION_LOG_COMMENT_CLIENT_BILLING_ACCOUNT_VIEW_DECRYPTED_DATA" : "TRANS_ACTION_LOG_COMMENT_CLIENT_BILLING_ACCOUNT"),
						array("ACCOUNT_NAME" => Factory()->ClientBillingAccount($billingAccountID)->getAccountNameForList(), "ACCOUNT_ID" => $billingAccountID, "CLIENT_ID" => $clientID),
						SecurityManager::getActionLogLocale()
					)
				);

				$this->smartyVars["client"] = correctArray($results["clients"][0]["client"][0]);
				$this->smartyVars["contact"] = correctArray($results["clients"][0]["client"][0]["contacts"][0]["contact"][0]);
				$this->smartyVars["billingAccount"] = collapseArrayElements($results["clients"][0]["client"][0]["billingAccounts"][0]["billingAccount"][0]);
				require_once("object_managers/ClientBillingAccountManager.php");
				$this->smartyVars["billingAccountTypes"] = ClientBillingAccountManager::getAllowedBillingAccountTypes($client);
				$this->smartyVars["billingAccountTypeName"] = ClientBillingAccount::typeName($this->smartyVars["billingAccount"]["billingAccountType"]);
                $this->smartyVars["ccAccount"] = ClientBillingAccount::TYPE_CREDIT_CARD;
                $this->smartyVars["manualAccount"] = ClientBillingAccount::TYPE_MANUAL_PAYMENT;
                $this->smartyVars["thirdPartyAccount"] = ClientBillingAccount::TYPE_THIRD_PARTY_GATEWAY;
                $this->smartyVars["bankTransferAccount"] = ClientBillingAccount::TYPE_HSPC_BANK_TRANSFER;
                require_once('objects/PaymentGateway.php');
                $this->smartyVars["bankAccountTypes"] = blmsg_array(PaymentGateway::bank_types());
				$this->smartyVars["cardTypes"] = blmsg_array(PaymentGateway::card_types());
				$this->smartyVars["cardExtraTypes"] = PaymentGateway::getCardTypeIdsWithExtraFields();

				require_once("objects/PaymentGateway.php");
				$bt_gateways = Factory()->PaymentGatewayList(array("payment_gateway_type" => PaymentGateway::TYPE_HSPC_BANK_TRANSFER, 'vendor_id' => $client->vendor_id));
				if (0 < count($bt_gateways)) {
					$billing_account = Factory()->ClientBillingAccount($billingAccountID);
					$billing_account_gateway_id = $billing_account->payment_gateway_id;
					$additional_form_values = array();
					foreach ($bt_gateways as $bt_gateway) {
						$plugin = ModuleTool::getModuleInstance("gateway", "HSPCBankTransfer", array("gateway_id" => $bt_gateway->id));
						$billing_account->payment_gateway_id = $bt_gateway->id;
						$adapter_input_fields = $plugin->getPaymentMethodAdapter($billing_account)->getInputFields();
						$input_fields = array();
						foreach ($adapter_input_fields as $field_name => $field_opts) {
							$input_fields[] = array(
								"field_name" => $field_name = "{$field_name}_{$bt_gateway->id}",
								"field_title" => $field_opts[0],
								"field_desc" => $field_opts[2]
							);
							$additional_form_values[$field_name] = $field_opts[1];
						}
						$this->smartyVars["ddbp_accounts"][] = array(
							"gateway_id" => $bt_gateway->id,
							"gateway_name" => $bt_gateway->payment_gateway_name,
							"gateway_desc" => $bt_gateway->payment_gateway_description,
							"fields" => $input_fields,
						);
					}
					$billing_account->payment_gateway_id = $billing_account_gateway_id;
					$this->smartyVars["selected_ddbp_gateway_id"] = bgpc("selected_ddbp_gateway_id", $billing_account_gateway_id);
				}

				// subscriptions
				$this->smartyVars["selectedPackages"] = grabHTMLOpsFromArray(grabResultsFromMBAPIArray(array(
					"mbapi" => array(
						"command" => "GetBillingAccountShares",
						"params" => array(
							"billingAccountID" => $billingAccountID,
							"getPackageData" => 1,
							"billingAccountShareValueGreaterThan" => 0
						),
					),
				)), "packageID", "baMakePackageName");
				$this->smartyVars["selectablePackages"] = grabHTMLOpsFromArray(grabResultsFromMBAPIArray(array(
					"mbapi" => array(
						"command" => "GetPackages",
						"params" => array(
							"clientID" => $clientID,
							"packageActive" => 1,
							"suppressFeePackages" => 1
						),
					),
				)), "packageID", "baMakePackageName", array_keys($this->smartyVars["selectedPackages"]));

				$defaults = $this->smartyVars["billingAccount"];
				if (!is_null($billingAccountType = bgpc('billingAccountType')))	{
					$defaults = array('billingAccountType' => $billingAccountType);
				}

				$this->mergeFormState($defaults);
				$this->smartyVars["paymentQueue_enableAdvancedShareEditing"] = Settings(Factory()->Client($clientID)->vendor_id)->paymentQueue_enableAdvancedShareEditing;
				if(is_array($additional_form_values)) {
					$this->smartyVars["formValues"] = array_merge($this->smartyVars["formValues"], $additional_form_values);
				}
				$this->addTemplate("clients/EditBillingAccount", $this->smartyVars);
			}
		}

		$this->addErrorTemplates();
		return $this->hasExecutedSuccessfully();
	}
}

function baMakePackageName($row)
{
	return "(".TRANS_ID.": ".$row["packageID"].") ".$row["packageName"];
}
