/**
  * Creates and returns the HTML form for initialising the
  * Postfinance Mobile payment.
  *
  * Fields:
  *  - Mandatory:
  *      currency    ISO 4217 currency code (only CHF for the time being)
  *      amount      Amount in cents (2.50 CHF = 250)
  *      orderid     Unique order ID
  *      webuser     The Mobilesolutions webuser name
  *      sign        SHA-1 Signature
  *      urlsuccess  Target URL after successful payment
  *      urlerror    Target URL after failed payment
  *  - Optional:
  *      customparam     Parameters to be appended to the success or error URL
  *      ijustwanttotest Enables the test mode if present
  * @param   integer   $amount           The order amount in cents
  * @param   integer   $order_id         The order ID
  * @param   string    $customparam      The optional custom parameter(s)
  * @param   boolean   $ijustwanttotest  Enable test mode if true
  * @return  mixed                       The HTML form on success, false
  *                                      otherwise
  * @static
  */
 static function getForm($amount, $order_id, $customparam = '', $ijustwanttotest = null)
 {
     global $_ARRAYLANG, $_CONFIG;
     if (!isset($ijustwanttotest)) {
         $ijustwanttotest = \Cx\Core\Setting\Controller\Setting::getValue('postfinance_mobile_ijustwanttotest', 'Shop');
     }
     if (empty($amount)) {
         self::$arrError[] = sprintf($_ARRAYLANG['TXT_SHOP_POSTFINANCE_MOBILE_ERROR_INVALID_AMOUNT'], $amount);
         return false;
     }
     if (empty($order_id)) {
         self::$arrError[] = sprintf($_ARRAYLANG['TXT_SHOP_POSTFINANCE_MOBILE_ERROR_INVALID_ORDER_ID'], $order_id);
         return false;
     }
     $currency = \Cx\Modules\Shop\Controller\Currency::getActiveCurrencyCode();
     if (empty($currency)) {
         self::$arrError[] = $_ARRAYLANG['TXT_SHOP_POSTFINANCE_MOBILE_ERROR_FAILED_TO_DETERMINE_ACTIVE_CURRENCY'];
         return false;
     }
     $webuser = \Cx\Core\Setting\Controller\Setting::getValue('postfinance_mobile_webuser', 'Shop');
     if (empty($webuser)) {
         self::$arrError[] = $_ARRAYLANG['TXT_SHOP_POSTFINANCE_MOBILE_ERROR_FAILED_TO_DETERMINE_WEBUSER'];
         return false;
     }
     $sign = \Cx\Core\Setting\Controller\Setting::getValue('postfinance_mobile_sign', 'Shop');
     if (empty($sign)) {
         self::$arrError[] = $_ARRAYLANG['TXT_SHOP_POSTFINANCE_MOBILE_ERROR_FAILED_TO_DETERMINE_SIGNATURE'];
         return false;
     }
     $signature = hash_hmac('sha1', $amount . $currency . $order_id . $webuser, pack('H*', $sign));
     $urlsuccess = Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'success')->toString() . '?handler=mobilesolutions&result=1' . '&order_id=' . $order_id;
     $urlerror = Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'success')->toString() . '?handler=mobilesolutions&result=0' . '&order_id=' . $order_id;
     /*
     Live URIs:
     https://postfinance.mobilesolutions.ch/webshop/handyzahlung
     http://api.smsserv.ch/webshop/handyzahlung
     
     Test URIs:
     https://postfinance.mobilesolutions.ch/shoptest/handyzahlung
     http://api.smsserv.ch/shoptest/handyzahlung
     
     On the testing environment, use the flag "ijustwanttotest", the mobile
     phone number 079 999 99 99, and the security code 12345678 to enforce
     a successful payment.  Any other numbers will produce a failed transaction.
     */
     return $_ARRAYLANG['TXT_ORDER_LINK_PREPARED'] . "<br/><br/>\n" . '<form name="postfinancemobile" method="post" ' . 'action="' . ($ijustwanttotest ? 'https://postfinance.mobilesolutions.ch/shoptest/handyzahlung' : 'https://postfinance.mobilesolutions.ch/webshop/handyzahlung') . '">' . "\n" . '<input type="hidden" name="currency" value="' . $currency . '" />' . "\n" . '<input type="hidden" name="amount" value="' . $amount . '" />' . "\n" . '<input type="hidden" name="orderid" value="' . $order_id . '" />' . "\n" . '<input type="hidden" name="webuser" value="' . $webuser . '" />' . "\n" . '<input type="hidden" name="sign" value="' . $signature . '" />' . "\n" . '<input type="hidden" name="urlsuccess" value="' . $urlsuccess . '" />' . "\n" . '<input type="hidden" name="urlerror" value="' . $urlerror . '" />' . "\n" . ($customparam ? '<input type="hidden" name="customparam" value="' . urlencode($customparam) . '" />' . "\n" : '') . ($ijustwanttotest ? '<input type="hidden" name="ijustwanttotest" value="1" />' . "\n" : '') . '<input type="submit" name="bsubmit" value="' . $_ARRAYLANG['TXT_SHOP_POSTFINANCE_MOBILE_SUBMIT'] . '" />' . "\n" . '</form>' . "\n";
 }
    /**
     * @return string|boolean
     */
    public static function getModalCode()
    {
        global $_CONFIG;
        $settingDb = \Cx\Core\Setting\Controller\Setting::getArray('Shop', 'config');
        if (empty($settingDb) || !$settingDb['payrexx_active']['value']) {
            self::$arrError[] = "Could not load settings.";
            return false;
        }
        $arrSettings = $settingDb;
        $instanceName = !empty($arrSettings['payrexx_instance_name']['value']) ? $arrSettings['payrexx_instance_name']['value'] : '';
        $apiSecret = !empty($arrSettings['payrexx_api_secret']['value']) ? $arrSettings['payrexx_api_secret']['value'] : '';
        if (empty($instanceName) || empty($apiSecret)) {
            self::$arrError[] = "Wrong Payrexx instance name or Payrexx API secret";
            return false;
        }
        $order = \Cx\Modules\Shop\Controller\Order::getById($_SESSION['shop']['order_id']);
        $payrexx = new \Payrexx\Payrexx($instanceName, $apiSecret);
        $invoice = new \Payrexx\Models\Request\Invoice();
        $invoice->setReferenceId('Shop-' . $order->id());
        $invoice->setTitle($_CONFIG['coreGlobalPageTitle']);
        $invoice->setDescription('&nbsp;');
        // We have to set all known PSPs to support all PSPs.
        // Known PSP are listed on https://payrexx.readme.io/docs/miscellaneous
        $invoice->setPsp(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23));
        $invoice->setName('Contrexx Shop Order: #' . $_SESSION['shop']['order_id']);
        $invoice->setPurpose('Shop Order #' . $_SESSION['shop']['order_id']);
        $invoice->setAmount(intval(bcmul($_SESSION['shop']['grand_total_price'], 100, 0)));
        $invoice->setCurrency(\Cx\Modules\Shop\Controller\Currency::getCodeById($order->currency_id()));
        $invoice->addField('email', false, $order->billing_email());
        $invoice->addField('company', false, $order->billing_company());
        $invoice->addField('forename', false, $order->billing_firstname());
        $invoice->addField('surname', false, $order->billing_lastname());
        $invoice->addField('street', false, $order->billing_address());
        $invoice->addField('postcode', false, $order->billing_zip());
        $invoice->addField('place', false, $order->billing_city());
        try {
            /**
             * @var \Payrexx\Models\Response\Invoice $invoice
             */
            $invoice = $payrexx->create($invoice);
        } catch (\Payrexx\PayrexxException $e) {
            self::$arrError[] = $e->getMessage();
            return false;
        }
        $successPage = \Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'success');
        $successPageUrl = $successPage->toString();
        try {
            $link = $invoice->getLink() . '&RETURN_URL=' . base64_encode($successPageUrl);
        } catch (\Cx\Core\Routing\UrlException $e) {
            self::$arrError[] = 'Could not find success page for shop module!';
            return false;
        }
        \header('Location: ' . $link);
        exit;
        // modal solution, not yet implemented
        $modalJs = \Cx\Core\Core\Controller\Cx::instanciate()->getCodeBaseModuleWebPath() . '/Shop/payments/payrexx/modal.js';
        $jqueryJs = \Cx\Core\Core\Controller\Cx::instanciate()->getCodeBaseOffsetPath() . '/lib/javascript/jqeury/2.0.2/js/jquery.min.js';
        $code = <<<EOF
<a style="display: none;" class="payrexx-modal-window" href="#" data-href="{PAYREXX_LINK}"></a>
<script type="text/javascript" src= "{$jqueryJs}"></script>
<script type="text/javascript">
    cx.jQuery = jQuery.noConflict();
</script>
<script type="text/javascript" src= "{$modalJs}"></script>
<script type="text/javascript">
    cx.ready(function() {
        cx.jQuery(".payrexx-modal-window").payrexxModal({
            hideObjects: ["#contact-details", ".contact"],
            hidden: function (transaction) {
                location.href = "{$successPageUrl}";
            }
        });
        cx.jQuery(".payrexx-modal-window").click();
    });
</script>
EOF;
        $code = str_replace('{PAYREXX_LINK}', $link, $code);
        return $code;
    }
 /**
  * Set up the mandatory parameters
  *
  * @param   integer $merchantId     The Datatrans merchant ID
  * @param   string  $refno          The unique merchant reference number,
  *                                  aka order ID
  * @param   string  $amount         The amount, in cents
  * @param   string  $currency       The three letter currency code
  * @return  boolean                 True on success, false otherwise
  */
 static function initialize($merchantId, $refno, $amount, $currency)
 {
     //echo("Datatrans::initialize(merchantId $merchantId, refno $refno, amount $amount, currency $currency): Entered<br />");
     /**
      * Currency: Conversion, formatting.
      */
     self::$arrFieldMandatory['merchantId'] = trim(strip_tags($merchantId));
     self::$arrFieldMandatory['refno'] = trim(strip_tags($refno));
     self::$arrFieldMandatory['amount'] = \Cx\Modules\Shop\Controller\Currency::formatCents($amount);
     self::$arrFieldMandatory['currency'] = trim(strip_tags($currency));
     if (empty($merchantId) || empty($refno) || empty($amount) || empty($currency)) {
         //die("Datatrans::initialize(): Failed - invalid parameters: merchantId $merchantId, refno $refno, amount $amount, currency $currency");
         return false;
     }
     //echo("Datatrans::initialize(): SUCCESS - parameters: ".var_export(self::$arrFieldMandatory, true)."<br />");
     return true;
 }