<?php
require_once("lib-action/genericactions.php");

class EditBillingAccount extends EditAction
{
	public function __construct()
	{
		global $CONF;
		$clientContactID = $CONF["user"]["clientContactID"];
		$clientID = (int)$CONF["user"]["id"];

		$contacts = arrayFor(":contacts", array(
			"clientID" => $clientID,
		));

		$keyedContacts = array();
		foreach ($contacts as $x=>$c){
			$keyedContacts[$c["clientContactID"]] =& $contacts[$x];
		}

		$this->smartyVars['isPrimary'] = $keyedContacts[$clientContactID]['contactPrimary'];

		$this->smartyVars['client'] = oneByID(":clients", $CONF['user']['id']);

		// if we are the primary contact and we can edit the billing accounts of
		// any contact for this client, else just edit our own
		if ((int)$keyedContacts[$clientContactID]["contactPrimary"] && is_array($keyedContacts[(int)$_REQUEST["clientContactID"]])){
			$clientContactID = (int)$_REQUEST["clientContactID"];
		}
		$_REQUEST["clientContactID"] = $clientContactID;

		$this->d = new DataSource("billingAccounts", array("clientContactID" => $clientContactID));
		$description = $this->d->getDescription();
		$description["names"]["file"] = "profile";
		$description["display"]["editTemplate"] = "profile/EditBillingAccount";
		$this->d->setDescription($description);
		parent::EditAction();
	}

	function editParamHandler()
	{
		global $CONF;
		$clientID = $CONF["user"]["id"];
		$clientContactID = $CONF["user"]["clientContactID"];
		$billingAccountID = bgpc("billingAccountID");

		// Repair billing account. This operation needed for BA created befre 7.0.1 for HSPC Bank Trabsfer payments.
		require_once("object_managers/ClientBillingAccountManager.php");
		ClientBillingAccountManager::repairAccount(Factory()->ClientBillingAccount($billingAccountID));

		require_once("object_managers/SecurityManager.php");
		SecurityManager::pushCurrentActionIntoLog(
			SecurityManager::USER_TYPE_CLIENT,
			$clientID,
			Factory()->Client($clientID)->PrimaryContact->contact_username,
			"TRANS_ACTION_LOG_REASON_SHOW_BILLING_ACCOUNT_DETAILS",
			blmsg(
				"TRANS_ACTION_LOG_COMMENT_CLIENT_BILLING_ACCOUNT",
				array("ACCOUNT_NAME" => Factory()->ClientBillingAccount($billingAccountID)->getAccountNameForList(), "ACCOUNT_ID" => $billingAccountID, "CLIENT_ID" => $clientID),
				SecurityManager::getActionLogLocale()
			)
		);

		$contact = oneByID(":contacts", $clientContactID);
		$this->smartyVars['isPrimary'] = $contact['contactPrimary'];

		$this->smartyVars['client'] = oneByID(":clients", $CONF['user']['id']);

		loadConfigs("payment");

		$this->smartyVars["billingAccountTypes"] = getTypes("billingAccount");

		$this->smartyVars["bankAccountTypes"] = getTypes("bankAccount");
		$this->smartyVars["cardExtraTypes"] = getTypes("cardExtraIDs");

		require_once("objects/PaymentGateway.php");
		$billing_account = Factory()->ClientBillingAccount($billingAccountID);
		$this->smartyVars["ddbpFormValues"] = array();

		if (ClientBillingAccount::TYPE_HSPC_BANK_TRANSFER == $billing_account->billing_account_type) {
			$bt_gateway = Factory()->PaymentGateway($billing_account->payment_gateway_id);
			$this->smartyVars["selected_ddbp_gateway_id"] = $bt_gateway->id;

			$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_title" => $field_opts[0],
					"field_desc" => $field_opts[2],
				);
				$this->smartyVars["ddbpFormValues"][$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,
			);
		} else {
			unset($this->smartyVars["billingAccountTypes"][PaymentGateway::TYPE_HSPC_BANK_TRANSFER]);
		}

		$this->smartyVars["selectedPackages"] = array();
		foreach (Factory()->ClientBillingAccountShareList(array('billing_account_id' => $billingAccountID)) as $share) {
			if ($share->billing_account_share_value == 0) {
				continue;
			}
			$this->smartyVars["selectedPackages"][$share->package_id] = '(ID: ' . $share->package_id . ') ' . $share->Package->package_name;
		}

		$ptypes = $CONF["types"]["products"];
		unset($ptypes[getAPITypeID("products", "fee")]);
		$packages = arrayFor(":packages", array(
			"clientID" => $clientID,
			"packageActive" => 1,
			"packageType" => array_keys($ptypes),
			"column" => array(
				"packageID", "packageName"
			),
		));

		$this->smartyVars["selectablePackages"] = array();
		foreach ($packages as $p){
			if (!isset($this->smartyVars["selectedPackages"][$p["packageID"]])){
				$this->smartyVars["selectablePackages"][$p["packageID"]] = "(ID: ".$p["packageID"].") ".$p["packageName"];
			}
		}

		$d = new DataSource(
			"gwTransactions",
			array(
				"billingAccountID" => $billingAccountID,
				"gwTransactionType" => "reject",
				"groupBy" => array(
					"column" => "paymentGatewayID",
				),
				"column" => "paymentGatewayID",
			)
		);
		$t =& $d->getTable();
		$gatewayIDs = $t->getColumnDistinct("paymentGatewayID");

		$rejects = array();
		foreach($gatewayIDs as $gatewayID) {
			$reject = oneOf(
				"gwTransactions",
				array(
					"billingAccountID" => $billingAccountID,
					"gwTransactionType" => "reject",
					"paymentGatewayID" => $gatewayID,
					"gwTransactionAttrs" => array(),
					"sortColumn" => "gwTransactionID",
					"sortDir" => "DESC",
					"numRecords" => 1,
				)
			);
			$t = new Table($reject["gwTransactionAttrs"], "gwTransactionAttrName", "gwTransactionAttrValue");
			$reject["attrs"] = $t->getOptions();
			$rejects[] = $reject;
		}
		$this->smartyVars["rejects"] = $rejects;

        require_once("object_managers/PaymentGatewayManager.php");
        $this->smartyVars["cardTypes"] = PaymentGatewayManager::getCardTypes();
		return true;
	}
}