<?php include("components/payment/paymentMethods.vue"); ?>
Vue.component('event-payment', {
  props: ['transaction','goback','confirm_order'],
  inject: ['_f','_get','validate','session_path','handleError','generateUUID'],
  data: () => ({
    loading: false,
    pc_loading: false,
    submitted: false,
    promoCode: null,
  }),
  computed: {
    isInWhiteLabel() {
      return localStorage.getItem('isInWhiteLabel')
    },
    whiteLabel() {
      return {
        white_label_name: localStorage.getItem('brandName'),
        white_label_color: localStorage.getItem('brandColor'),
        white_label_mode: localStorage.getItem('brandDark'),
        white_label_logo: localStorage.getItem('brandLogo')
      }
    }
  },
  mounted () {
    window.payment = this
  },
  methods: {
    nextStep(){
      this.createPayment();
    },
    applyPromoCode() {
      this.pc_loading = true;
      axios.post("<?=$apiEndpoint;?>"+'event_transactions/apply_discount_code', {
        token: this.transaction.token,
        discount_code: this.promoCode,
      }).then(res=> {
        this.pc_loading = false;
        this.promoCode = null;
        let code = res.data.data;
        if (code.discount_price > 0) {
          dataLayer.push({
            'event': 'apply-promo-code',
            'code': code.discount_code,
            'value': code.discount_price,
            'currency': code.currency,
            'payment_price': code.payment_price,
            'event_name': this.transaction.fields.event_title,
            'event_category': this.transaction.event_category.fields.default.title, // this.transaction.event_category_id,
            'event_brand': this.transaction.fields.organizer_title, // this.transaction.organizer_id,
          });
        }

        this.$emit('refresh');
        swal(this.$t('success.PromoCode.title', {currency: code.currency, discount: code.discount_price}),"","success");
      }).catch(err=>{
        this.pc_loading = false;
        if(err.status === 403){
          swal(this.$t('error.PromoCode.title'),"","error");
        } else {
          this.handleError(err);
        }
      });
    },
    createPayment() {
      this.loading = true;
      if (this.transaction.payment_price > 0) {
        if (this.$refs.payment_methods.$refs.payment_methods.validate()) {
          axios.post("<?=$apiEndpoint;?>"+`payments`, {
            object: "event_transaction",
            object_token: this.transaction.token,
            method_type: "card",
            service: this.transaction.service,
          }).then(res => {
            if (res.data.result === 'success') {
              dataLayer.push({
                'event': 'checkout',
                'ecommerce': {
                  'checkout': {
                    'actionField': {'step': 2, 'option': this.transaction.service},
                    'products': this.transaction.grouped_tickets.map(variant => ({
                      'id': this.transaction.event_id,
                      'name': this.transaction.fields.event_title,
                      'category': this.transaction.event_category.fields.default.title, // this.transaction.event_category_id,
                      'brand': this.transaction.fields.organizer_title, // this.transaction.organizer_id,
                      'event_tag': this.transaction.fields.event_tags ? this.transaction.fields.event_tags + ',' : '',
                      'variant_id': variant.event_ticket_id,
                      'variant': variant.fields.event_ticket_title,
                      'quantity': variant.quantity,
                      'price': parseFloat(variant.unit_payment_price)
                    }))
                  }
                }
              });
              fbq('track', 'AddPaymentInfo', { 
                env: "<?=$env;?>",
                event_id: this.transaction.event_id,
                event_tag: this.transaction.fields.event_tags ? this.transaction.fields.event_tags + ',' : '',
                event_category_id: this.transaction.event_category_id,
                event_location: this.transaction.country_id,
                currency: this.transaction.currency,
                value: parseFloat(this.transaction.payment_price),
                coupon: this.transaction.fields.discount_code
              });
              this.handleCheckout(res.data.data);
            }
          }).catch(err => {
            this.loading = false;
            if (err.status === 404) {
              swal(this.$t('error.UpdateTransaction.404'),'','warning').then(()=>{
                this.backToEvent();
              });
            } else {
              this.handleError(err);
            }
          });
        } else {
          this.loading = false;
          this.$root.showToast({text: this.$t('form.invalid'), zindex:301}, "warning");

          var first_invalid_el = (this.$refs.payment_methods.$refs.payment_methods.$children).filter(input=>Array.isArray(input.errorBucket) && (input.errorBucket.length>0))[0];
          first_invalid_el && first_invalid_el.$el.scrollIntoView({behavior: "smooth", block: "center"});
        }
      } else {
        this.transaction.status = "succeeded";
        axios.patch("<?=$apiEndpoint;?>"+`event_transactions/${this.transaction.token}`, this.transaction).then(res => {
          this.loading = false;
          dataLayer.push({
            'event': 'checkout',
            'ecommerce': {
              'checkout': {
                'actionField': {'step': 2, 'option': 'N/A'},
                'products': this.transaction.grouped_tickets.map(variant => ({
                  'id': this.transaction.event_id,
                  'name': this.transaction.fields.event_title,
                  'category': this.transaction.event_category.fields.default.title, // this.transaction.event_category_id,
                  'brand': this.transaction.fields.organizer_title, // this.transaction.organizer_id,
                  'event_tag': this.transaction.fields.event_tags ? this.transaction.fields.event_tags + ',' : '',
                  'variant_id': variant.event_ticket_id,
                  'variant': variant.fields.event_ticket_title,
                  'quantity': variant.quantity,
                  'price': parseFloat(variant.unit_payment_price)
                }))
              }
            }
          });
          fbq('track', 'AddPaymentInfo', { 
            env: "<?=$env;?>",
            event_id: this.transaction.event_id,
            event_tag: this.transaction.fields.event_tags ? this.transaction.fields.event_tags + ',' : '',
            event_category_id: this.transaction.event_category_id,
            event_location: this.transaction.country_id,
            currency: this.transaction.currency,
            value: parseFloat(this.transaction.payment_price),
            coupon: this.transaction.fields.discount_code
          });
          var current_params = new URLSearchParams(window.location.search);
          location.assign(this.session_path+"order/"+(res.data.data.token)+"?"+current_params.toString());
        }).catch(err => {
          this.loading = false;
          this.handleError(err);
        })
      }
    },
    handleCheckout (data) {
      switch (data.service) {
        case 'cybersource':
        case 'cybersource_boc':
          this.handleCybersourceCheckout(data);
          break;
        case 'stripe':
          this.handleStripeCheckout(data);
          break;	
        case 'unionpay':
          this.handleUnionPayCheckout(data);
          break;			
        default:
          break;
      }
    },
    handleStripeCheckout (data) {
      let _this = this;
      Stripe("<?=$STRIPE_PUBLIC_KEY;?>").redirectToCheckout({
        sessionId: data.settings.checkout_session_id,
      }).then(function (result) {
        if(!result.error) {
          // redirect
          // console.log(result);
        } else {
          _this.loading = false;
          swal("Stripe Error", result.error.message, "error");
        }
      });
    },
    handleCybersourceCheckout (data) {
      let form = document.createElement("form");
      form.setAttribute('style','display:none');
      form.method = "POST";
      let	override_custom_cancel_page = "<?=$host_url.$session_path;?>" + 'order/' + data.paymentable.token + '?lang=' + this.$i18n.locale + '&cancelled=1';
      let	override_custom_receipt_page = "<?=$host_url.$session_path;?>" + 'order/' + data.paymentable.token + '?lang=' + this.$i18n.locale;
      if (window.location !== window.parent.location) {
        form.target = "_top";
        override_custom_cancel_page = "https://" + data.paymentable.fields.event_domain + "/" + data.paymentable.fields.event_url_string + '/payment/' + data.paymentable.token + '?lang=' + this.$i18n.locale + '&cancelled=1';
        override_custom_receipt_page = "https://" + data.paymentable.fields.event_domain + "/" + data.paymentable.fields.event_url_string + '/payment/' + data.paymentable.token + '?lang=' + this.$i18n.locale;
      }
      form.action = "<?=$CYBERSOURCE_FORM_POST;?>";
      let inputs = {
        access_key: "<?=$CYBERSOURCE_ACCESS_KEY;?>",
        profile_id: "<?=$CYBERSOURCE_PROFILE_ID;?>",
        transaction_uuid: this.generateUUID(),
        signed_field_names: "bill_to_address_country,bill_to_email,bill_to_forename,bill_to_surname,bill_to_address_city,bill_to_address_line1,override_custom_cancel_page,override_custom_receipt_page,access_key,profile_id,transaction_uuid,signed_field_names,unsigned_field_names,signed_date_time,locale,transaction_type,reference_number,amount,currency",
        unsigned_field_names: "",
        signed_date_time: data.created_at.split('.')[0]+"Z", // new Date().toISOString().split('.')[0]+"Z",
        locale: data.paymentable.locale.replace(/_/g, "-"),
        transaction_type: "sale",
        reference_number: data.paymentable.code,
        amount: data.price,
        currency: data.currency,
        bill_to_address_country: data.paymentable.country_code,
        bill_to_email: data.paymentable.user_email,
        bill_to_forename: data.paymentable.user_first_name,
        bill_to_surname: data.paymentable.user_last_name,
        bill_to_address_city: 'N/A',
        bill_to_address_line1: 'N/A',
        override_custom_cancel_page: override_custom_cancel_page,
        override_custom_receipt_page: override_custom_receipt_page,
      };
      Object.keys(inputs).forEach((name) => {
        let input = document.createElement("input"); 
        input.name = name;
        input.value = inputs[name];
        form.appendChild(input); 
      });
      axios.post("<?=$host_url.$base_uri;?>" + 'php/cyber/getSign.php', inputs).then((res) => {
        let input = document.createElement("input");
        input.value= res.data.sign;
        input.name= "signature";
        form.appendChild(input); 
        
        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
      }).catch(err => {
        this.loading = false;
        console.error(err);
        this.handleError(err);
      });
    },
    handleUnionPayCheckout (data) {
      try {
        location.assign(data.service_url); 
      } catch (err) {
        this.handleError(err);
      }
    }
    
  },
  template:
`<v-form ref="payment" class="payment border-width-1px">
  <v-row no-gutters>
    <v-col cols="12" lg="8" offset-lg="2" v-if="transaction">
      <v-card class="mb-3">
        <v-card-title class="pl-1">
          <v-row no-gutters align="center">
            <v-col cols="auto">
              <v-btn icon text @click="goback">
                <v-icon>mdi-chevron-left</v-icon>
              </v-btn>
            </v-col>
            <v-col>
              <h2 class='display-3 title'>{{ transaction.fields.event_title}}</h2>
            </v-col>
          </v-row>
        </v-card-title>
        <v-divider></v-divider>
        <!-- promo code -->
        <v-expansion-panels flat outlined>
          <v-expansion-panel class="no-padding py-3">
            <v-expansion-panel-header class="px-4" style="min-height:32px;">
              <h3 class='display-3 title primary--text'>{{$t('EventPayment.promoCode')}}</h3>
            </v-expansion-panel-header>
            <v-expansion-panel-content>
              <v-form ref="promo_code">
                <v-row dense align="center" class="px-4">
                  <v-col>
                    <v-text-field
                      v-model="promoCode"
                      :placeholder="$t('input.promo_code.placeholder')"
                      :rules="[
                        v=>(!!v) || $t('validation.required',{field: $t('input.promo_code.label')}),
                      ]"
                      :hide-details="submitted?'auto':true"
                      @keypress.enter.prevent="applyPromoCode"
                      outlined
                      single-line
                      hide-details
                      required
                      dense
                      color="primary"
                    ></v-text-field>
                  </v-col>
                  <v-col cols="auto">
                    <v-btn color="primary" class="ma-0" :loading="pc_loading" :outlined="promoCode==null" @click="applyPromoCode">
                      {{$t('button.apply')}}
                    </v-btn>
                  </v-col>
                </v-row>
              </v-form>
            </v-expansion-panel-content>
          </v-expansion-panel>
        </v-expansion-panels>
        <v-divider></v-divider>
        <!-- order details -->
        <v-card-text>
          <h3 class='display-3 title primary--text'>{{$t('EventPayment.purchaseItems')}}</h3>
          <v-row dense class="subtitle-1 px-2">
            <v-col cols="8" md="4">{{$t('EventPayment.ticketType')}}</v-col>
            <v-col md="2" class="hidden-sm-and-down">{{$t('EventPayment.ticketPrice')}}</v-col>
            <v-col md="2" class="hidden-sm-and-down">{{$t('EventPayment.ticketServiceFee')}}</v-col>
            <v-col md="2" class="hidden-sm-and-down">{{$t('EventPayment.ticketQuantity')}}</v-col>
            <v-col cols="4" md="2" class="text-right">{{$t('EventPayment.ticketSubtotal')}}</v-col>
          </v-row>
          <v-card outilned class="subtitle-1 py-2 px-3" style="border-radius: 12px;">
            <div v-for="(ticket, index) in transaction.grouped_tickets" v-bind:key="index">
              <v-row dense>
                <v-col cols="8" md="4">{{ ticket.fields.event_ticket_title }}
                  <div class="hidden-md-and-up">
                    {{ $t('EventPayment.eachPerTicket', {quantity:ticket.quantity, price: (transaction.currency+''+ticket.unit_face_value), fee: (transaction.currency+''+ticket.unit_user_fee)}) }}
                  </div>
                </v-col>
                <v-col md="2" class="hidden-sm-and-down">{{((~~(transaction.fields && transaction.fields.hide_free_ticket_price) && 0>=ticket.unit_user_fee))?'−−':(transaction.currency+''+ticket.unit_face_value)}}</v-col>
                <v-col md="2" class="hidden-sm-and-down">{{((~~(transaction.fields && transaction.fields.hide_free_ticket_price) && 0>=ticket.unit_user_fee))?'−−':(transaction.currency+''+ticket.unit_user_fee)}}</v-col>
                <v-col md="2" class="hidden-sm-and-down">{{ticket.quantity}}</v-col>
                <v-col md="2" class="text-right" v-if="ticket.face_value>0">{{transaction.currency}}{{ticket.face_value + ticket.user_fee}}</v-col>
                <v-col cols="4" md="2" class="text-right" v-else>{{(~~(transaction.fields && transaction.fields.hide_free_ticket_price))?'−−':$t('EventPayment.free')}}</v-col>
              </v-row>
              <v-divider></v-divider>
            </div>
            <v-row dense v-if="transaction.discount_price>0">
              <v-col cols="10">
                <span>{{$t('EventPayment.discountCode')}}: {{_get(transaction,'fields.discount_code','')}}</span>
              </v-col>
              <v-col cols="2" class="text-right red--text">
                (-{{transaction.currency}}{{transaction.discount_price}})
              </v-col>
            </v-row>
          </v-card>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-text v-if="transaction.payment_price > 0">
          <h1 class='display-3 title pb-4 primary--text'>{{$t('EventPayment.paymentMethods')}}</h1>
          <payment-methods ref="payment_methods" :transaction="transaction"></payment-methods>
          <div class="pt-2 caption" v-if="this.transaction.service">
            {{$t('EventPayment.statementDescriptor',{descriptor: (transaction.service == 'cybersource' || transaction.service == 'unionpay' || transaction.service == 'cybersource_boc')?'WEWON':'1TICKS'})}}
          </div>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-text>
          <v-row justify-space-between>
            <v-col>
              <h4 class='display-3 title primary--text'>{{$t('EventPayment.ticketTotal')}}</h4>
            </v-col>
            <v-col cols="auto">
              <div class="title" v-if="transaction.payment_price > 0">{{transaction.currency}}{{(transaction.payment_price).toFixed(2)}}</div>
              <div class="title" v-else>{{(~~(transaction.fields && transaction.fields.hide_free_ticket_price))?'−−':$t('EventPayment.free')}}</div>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
      <v-row dense justify="center">
        <v-col cols="12" lg="4">
          <v-btn color="primary" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true" v-if="transaction.face_value > 0" :loading="loading" @click="nextStep" block>{{$t('EventPayment.confirmOrderButtonAndPay')}}</v-btn>
          <v-btn color="primary" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true" v-else :loading="loading" @click="nextStep" block>{{$t('EventPayment.confirmOrderButton')}}</v-btn>
        </v-col>
      </v-row>
    </v-col>
  </v-row>
</v-form>`
});