<?php

require_once "stripe.php";

class Am_Paysystem_StripeGooglePay extends Am_Paysystem_Stripe {

    protected $defaultTitle = "Google Pay";
    protected $defaultDescription = "";

    protected function _initSetupForm(Am_Form_Setup $form) {
        $form->addText('google_merchant_id')->setLabel(___('Google Pay Merchant ID'));
        $form->addAdvCheckbox("testing")
                ->setLabel("Is it a Sandbox (Developer) Account?");
    }

    function getConfig($key = null, $default = null) {
        if ($key == 'hosted')
            return true;

        return parent::getConfig($key, $this->getDi()->plugins_payment->loadGet('stripe')->getConfig($key, $default));
    }

    function createFormHosted(\Invoice $invoice, Am_Mvc_Controller_CreditCard_Stripe $controller) {

        $form = new Am_Form('cc-stripe');

        $public_key = $this->getConfig('public_key');
        $amount = $invoice->first_total * (pow(10, Am_Currency::$currencyList[$this->invoice->currency]['precision']));
        $currency = $invoice->currency;
        $email = $invoice->getEmail();
        $title = $this->getDi()->config->get('site_title');
        $subtitle = $invoice->getLineDescription();

        $form->addHidden('id')->setValue($controller->getRequest()->get('id'));

        $controller->view->headScript()->appendFile('https://pay.google.com/gp/p/js/pay.js');
        $cancelUrl = $this->getCancelUrl();
        $env = $this->getConfig('testing') ? 'TEST' : 'PRODUCTION';
        $merchant_id = $this->getConfig("google_merchant_id");
        $errMsg = ___('Error processing payment');
        $form->addRaw()->setContent(<<<CUT
   <style>
    .gpay-button{display:block!important;border-radius: 25px; margin:auto;}
   </style>
   <div id='google-pay-container'></div>
CUT
        );

        $form->addScript()->setScript(<<<CUT
   jQuery(document).ready(function(){
   var baseRequest = {
      apiVersion: 2,
      apiVersionMinor: 0
    };

    var tokenizationSpecification = {
      type: 'PAYMENT_GATEWAY',
      parameters: {
        'gateway': 'stripe',
        'stripe:publishableKey': '{$public_key}',
        'stripe:version': '1.5'
      }
    };
    var  allowedCardNetworks = ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"];

    var  allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];

    var  baseCardPaymentMethod = {
      type: 'CARD',
      parameters: {
        allowedAuthMethods: allowedCardAuthMethods,
        allowedCardNetworks: allowedCardNetworks
      }
    };

    var  cardPaymentMethod = Object.assign(
      {tokenizationSpecification: tokenizationSpecification},
      baseCardPaymentMethod
    );

    var  paymentsClient =
        new google.payments.api.PaymentsClient({environment: '{$env}'});

    var  isReadyToPayRequest = Object.assign({}, baseRequest);

    isReadyToPayRequest.allowedPaymentMethods = [baseCardPaymentMethod];

    paymentsClient.isReadyToPay(isReadyToPayRequest)
        .then(function(response) {
          if (response.result) {
            var button =
                paymentsClient.createButton({onClick: function(e){
                    e.preventDefault();
                    var paymentDataRequest = Object.assign({}, baseRequest);
                    paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
                      paymentDataRequest.transactionInfo = {
                        totalPriceStatus: 'FINAL',
                        totalPrice: '{$amount}',
                        currencyCode: '{$currency}'
                        };
                        paymentDataRequest.merchantInfo = {
                            merchantName: '{$title}',
			    merchantId: '{$merchant_id}'
                        };
                        paymentsClient.loadPaymentData(paymentDataRequest).then(function(paymentData){
                              var token = JSON.parse(paymentData.paymentMethodData.tokenizationData.token);
   jQuery("#cc-stripe").append(jQuery("<input type='hidden' name='stripeToken'>").val(token.id));
   jQuery("#cc-stripe").submit();

                        }).catch(function(err){
                            // show error in developer console for debugging
                            amFlashError(err.statusCode);
                            document.location.href='{$cancelUrl}';
                        });
                    }, 'buttonColor' : 'black', buttonType:'long'});
            jQuery('#google-pay-container').append(jQuery(button));

          }
        })
        .catch(function(err) {
          // show error in developer console for debugging
        console.log(err);
        amFlashError(err.statusMessage);
        document.location.href='{$cancelUrl}';
        });
});
CUT
        );

        return $form;
    }

}
