<?php
  include_once('settings/index.php');
  // error_reporting(0);
  $token = $_GET['code'];
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <?php if ($env !='prod'):?>
      <!-- no crawling -->
      <meta name="robots" content="none" /> 
    <?php else: ?>
      <meta name="keywords" content="1ticks,ticketing,ticketing tools,event ticketing,free ticketing system,event promotion,MacauTicket,kktix,juven,澳門售票,售票網,廣星,售票平台,舉辦活動,免費舉辦活動,活動推廣,活動行銷,宣傳活動">
      <meta name="robots" content="index,follow">
    <?php endif;?>

    <title>訂單狀態</title>
    <link rel="shortcut icon" href="<?=$host_url.$base_uri;?>static/favicon.ico" type="image/x-icon">
    <meta property="og:title" content="訂單狀態" />
    <meta name="twitter:title" content="訂單狀態" />
    
    <meta name="apple-mobile-web-app-capable" content="no">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="apple-mobile-web-app-title" content="1TICKS">
    <link rel="apple-touch-icon" href="<?=$host_url.$base_uri;?>static/apple-icons-150.png">
    <meta property="og:type" content="website" />
    <meta property="og:site_name" content="1TICKS" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@1TICKS" />

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
  <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="<?=$base_uri;?>css/component-styles.css" rel="stylesheet">
  <link href="<?=$base_uri;?>css/vuetify@2.x.min.css" rel="stylesheet">
  <link href="<?=$base_uri;?>css/quill.core.css" rel="stylesheet">

  <?php include_once('tracking.php');?>
  <style>
    [v-cloak] {
      display:none;
    }
    img {
      max-width: 100%;
    }
    .swal-modal {
      font-family: 'Verdana', 'Geneva', sans-serif !important;
    }
    .v-btn__content {
      white-space: normal;
      word-break: break-word;
      width: 100%;
    }
  </style>
</head>

<body>
<noscript>
  <strong>We're sorry but 1TICKS doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app">
  <v-app>
    <loading-widget :loading="loading_widget.loading"></loading-widget>
    <v-fade-transition>
      <app-toolbar v-if="event" :is_whitelabel="_get(event,'is_white_label',false)" :settings="_get(event,'settings',{})"></app-toolbar>
    </v-fade-transition>
    <v-main>
      <div class="page-wrapper">
        <v-container class="pa-0" fluid v-cloak>
          <section>
            <div v-if="transaction != null">
              <resend-ticket-dialog v-if="isInWhiteLabel" :shown="resendDialog" @close="resendDialog = false" :transaction="transaction"></resend-ticket-dialog>
              <div>
                <v-row dense>
                  <v-col cols="12" lg="8" offset-lg="2">
                    <!-- success order -->
                    <v-card v-if="transaction.status == 'succeeded'" class="pa-2">
                      <v-card-text>
                        <v-row dense align="center">
                          <v-col cols="auto">
                            <v-icon size="50" color="primary" class="pr-2">mdi-check-circle</v-icon>
                            <!-- <v-img class="ml-2 mr-3" contain :style="'height:40px;width:40px;'" :src="base_uri + 'static/images/ordered_completed.png'"></v-img> -->
                          </v-col>
                          <v-col>
                            <h2 class='headline primary--text'>{{transaction.payment_price>0?$t('PaymentCompleted.paymentSuccess'):$t('PaymentCompleted.orderSuccess')}}</h2>
                          </v-col>
                          <v-col class="text-right">
                            <h3 class="title">{{$t('PaymentCompleted.orderCode', {code:transaction.code})}}</h3>
                          </v-col>
                        </v-row>
                        <div class='pt-2 hidden-md-and-up'>
                          <v-img style='width:100%;' :alt="transaction.fields.event_title" :src="transaction.fields.event_image_url" aspect-ratio="1.91"></v-img>
                        </div>
                        <v-row dense align="center">
                          <v-col cols="12" sm="8">
                            <h2 class='font-weight-bold' :class="{'headline': $vuetify.breakpoint.mdAndUp, 'title': $vuetify.breakpoint.smAndDown}">{{ transaction.fields.event_title }}</h2>
                            <event-basic-info 
                              :openMap="openMap" 
                              :event="{
                                start_date: transaction.fields.event_start_date,
                                end_date: transaction.fields.event_end_date,
                                start_time: transaction.fields.event_start_time,
                                end_time: transaction.fields.event_end_time,
                                fields: { 
                                  default: {
                                    venue: transaction.fields.event_venue,
                                    address: transaction.fields.event_address,
                                  }
                                },
                                settings: {
                                  weekday: transaction.fields.event_weekday,
                                  hide_event_time: transaction.fields.hide_event_time,
                                },
                                organizer: {
                                  ...transaction.organizer,
                                },
                              }" 
                              :isInWhiteLabel="isInWhiteLabel" 
                              :whiteLabel="whiteLabel"
                            ></event-basic-info>
                            <div class="black--text">
                              <span style="vertical-align:baseline" class='subtitle-1 font-weight-bold text-no-wrap text-left pl-0 pr-3'>{{$t('EventPayment.purchaseItems')}}</span><div class="d-inline-block">
                                <div class="subtitle-1" v-for="(ticket, i) in transaction.grouped_tickets" :key="i">{{ticket.fields.event_ticket_title}} x {{ticket.quantity}}</div>
                              </div>
                            </div>
                          </v-col>
                          <v-col class='hidden-sm-and-down'>
                            <v-img style='width:100%;' :alt="transaction.fields.event_title" :src="transaction.fields.event_image_url" aspect-ratio="1.91"></v-img>
                          </v-col>
                        </v-row>
                        <v-row dense align="center">
                          <v-col cols="auto">
                            <v-icon size="44" class="px-3">mdi-email-send-outline</v-icon>
                          </v-col>
                          <v-col>
                            <v-row dense>
                              <v-col cols="12" pb-0>
                                <h3 style="word-break: break-word;" :class="{'headline': $vuetify.breakpoint.mdAndUp, 'title': $vuetify.breakpoint.lgAndDown}">{{$t('PaymentCompleted.emailSent', {email:transaction.user_email})}}</h3>
                                <!-- <h3>訂單編號: #{{completed_response.code}}</h3> -->
                              </v-col>
                              <v-col cols="12" md="6" v-if="isInWhiteLabel">
                                <v-btn @click="resendDialog = true" color="primary" block :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true">{{$t('PaymentCompleted.resentTicket')}}</v-btn>
                              </v-col>
                              <v-col cols="12" md="6" v-if="isInWhiteLabel">
                                <v-btn color="primary darken-1" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true" block @click="backToEvent">{{$t('PaymentCompleted.backToEventButton')}}</v-btn>
                              </v-col>
                              <v-col cols="12" v-if="!isInWhiteLabel">
                                <v-btn small class="mr-3" color="primary" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true" block :to="{ name: 'Account', hash: '#tickets'}">{{$t('PaymentCompleted.viewTickets')}}</v-btn>
                              </v-col>
                            </v-row>
                          </v-col>
                        </v-row>
                      </v-card-text>
                    </v-card>
                    <!-- void order -->
                    <v-card v-else-if="transaction.status == 'voided'" class="pa-2">
                      <v-card-text>
                        <v-row dense class="text-center text-sm-left" align="center">
                          <v-col cols="12" md="auto">
                            <v-btn class="pa-0" style="height:80px;width:80px;" color="error" depressed fab>
                              <v-icon size="80">mdi-close</v-icon>
                            </v-btn>
                          </v-col>
                          <v-col cols="12">
                            <h2 class='font-weight-bold primary--text' :class="{'headline': $vuetify.breakpoint.mdAndUp, 'title': $vuetify.breakpoint.lgAndDown}">{{$t('PaymentCompleted.voidedOrderTitle', {code:transaction.code})}}</h2>
                            <h3 class="mt-2" :class="{'headline': $vuetify.breakpoint.mdAndUp, 'title': $vuetify.breakpoint.lgAndDown}">{{$t('PaymentCompleted.voidedOrderSubtitle')}}</h3>
                            <v-btn class="mt-3" small color="primary" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true" block :to="{ name: 'Event', query: { lang: $i18n.locale }, params: { id: (transaction.fields.event_url_string || transaction.event_id) }}">{{$t('PaymentCompleted.backToEventButton')}}</v-btn>
                          </v-col>
                        </v-row>
                      </v-card-text>
                    </v-card>
                    <!-- unfinish order -->
                    <v-card v-else class="pa-2">
                      <v-card-text>
                        <v-row class="text-center text-sm-left">
                          <v-col cols="12" md="auto">
                            <v-btn class="pa-0" style="height:80px;width:80px;" color="error" depressed fab>
                              <v-icon size="80">mdi-close</v-icon>
                            </v-btn>
                          </v-col>
                          <v-col>
                            <h2 class='font-weight-bold primary--text' :class="{'headline': $vuetify.breakpoint.mdAndUp, 'title': $vuetify.breakpoint.lgAndDown}">
                              <span>{{$t('PaymentCompleted.unfinishedOrderTitle', {code:transaction.code})}}</span>
                              <v-btn small icon style="width:20px;height:20px;" color="primary" @click="getTransaction(true)">
                                <v-icon small>mdi-refresh</v-icon>
                              </v-btn>
                            </h2>
                            <div v-if="getUrlParam('cancelled') != 1">
                              <h3 class="my-2 text-xs-left" v-if="!isInWhiteLabel" :class="{'headline': $vuetify.breakpoint.mdAndUp, 'title': $vuetify.breakpoint.lgAndDown}" v-html="$t('PaymentCompleted.unfinishedOrderSubtitle')"></h3>
                              <h3 class="my-2 text-xs-left" v-else-if="transaction.price > 0" :class="{'headline': $vuetify.breakpoint.mdAndUp, 'title': $vuetify.breakpoint.lgAndDown}" v-html="$t('PaymentCompleted.unfinishedOrderSubtitleWhiteLabel')"></h3>
                            </div>
                            <v-row dense>
                              <v-col cols="12" sm6 order-sm2 py-0 v-if="!isInWhiteLabel">
                                <v-btn small color="primary" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true" block :to="{ name: 'Account', hash: '#tickets'}">{{$t('PaymentCompleted.viewTickets')}}</v-btn>
                              </v-col>
                              <v-col cols="12" sm6 py-0>
                                <v-btn small color="primary lighten-2" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true" block @click="backToEvent">{{$t('PaymentCompleted.backToEventButton')}}</v-btn>
                              </v-col>
                            </v-row>
                          </v-col>
                        </v-row>
                      </v-card-text>
                    </v-card>
                  </v-col>
                </v-row>
              </div>
            </div>
          </section>
        </v-container>
      </div>
    </v-main>
    <app-footer :is_whitelabel="_get(event,'is_white_label',false)" :settings="_get(event,'settings',{})" class="pb-5"></app-footer>

    <!-- snackbar -->
    <v-snackbar v-cloak
      bottom
      right
      class="d-flex"
      style="height: auto; user-select: none;"
      :style="(snackbar.zindex?'z-index:'+snackbar.zindex+';':'')+($vuetify.breakpoint.smAndDown?'padding-bottom:48px;':'')" 
      :timeout="snackbar.timeout"
      :color="snackbar.color"
      v-model="snackbar.show"
      v-touch="{
        move: () => (snackbar.show = false),
      }"
    >
      <v-icon v-if="snackbar.icon" :dark="snackbar.dark" style="cursor:pointer" @click="snackbar.show = false">{{snackbar.icon}}</v-icon>
      <span class="font-weight-bold px-2">{{ snackbar.text }}</span>
      <template v-slot:action="{ attrs }">
        <v-btn v-bind="attrs" v-if="snackbar.timeout<=0" dark @click.native="snackbar.show = false" icon> 
          <v-icon large>mdi-close</v-icon>
        </v-btn>
      </template>
    </v-snackbar> 
  </v-app>
</div>
<!-- vue script -->
<script src="<?=$base_uri;?>script/vue@2.x.min.js"></script>
<script src="<?=$base_uri;?>script/vuetify@2.x.min.js"></script>
<script src="<?=$base_uri;?>script/vue-i18n@8.21.1.min.js"></script>
<script src="<?=$base_uri;?>script/axios@0.19.2.min.js"></script>
<script src="<?=$base_uri;?>script/sweetalert@2.1.2.min.js"></script>
<!-- <script type="text/babel" data-presets="es2015, es2016, es2017, stage-3"> -->
<script>
"use strict";
(function() {
  <?php include("components/loadingWidget.vue");?>
  <?php include("components/appToolbar.vue");?>
  <?php include("components/appFooter.vue");?>
  <?php include("components/searchWidget.vue"); ?>
  <?php include("components/cMarquee.vue"); ?>
  <?php include("components/event/eventBasicInfo.vue"); ?>
  <?php include("components/order/resendTicketDialog.vue"); ?>

  <?php include_once('includes/tracker.js');?>

  var MessengerExtensions = MessengerExtensions || false;
  const i18n = new VueI18n({
    locale: 'zh_TW',
    messages: {
      zh_TW: <?php include_once('includes/lang/zh_TW.json');?>,
      zh_CN: <?php include_once('includes/lang/zh_CN.json');?>,
      en: <?php include_once('includes/lang/en.json');?>,
    }
  })
  Vue.prototype.is_mobile = /android|webos|iphone|ipad|ipod|blackberry|mobile|opera mini/i.test(navigator.userAgent.toLowerCase());
  Vue.prototype.is_iOS = /iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase());
  Vue.prototype.is_safari = /apple/i.test(navigator.vendor.toLowerCase());
  Vue.prototype.in_wechat = /micromessenger/i.test(navigator.userAgent.toLowerCase());
  Vue.prototype.in_alipay = /alipay/i.test(navigator.userAgent.toLowerCase());
  Vue.prototype.in_instagram = /instagram/i.test(navigator.userAgent.toLowerCase());

  var methods = { <?php include("./includes/methods.js");?> };
  var app = new Vue({
    el: '#app',
    i18n,
    vuetify: new Vuetify(<?php include("./includes/themes.js");?>),
    data: ()=>({
      // general
      loading: false,
      loading_widget: {
        loading: false,
      },
      snackbar: {
        show: false,
        timeout: -1,
        text: '',
        color: '',
      },
      // api
      base_uri: "<?=$base_uri;?>",
      session_path: "<?=$session_path;?>",
      // tracked
      tracked: {},
      // data
      code: "<?=$token;?>",
      event: null,

      rerequest_limits: 5,
      rerequest_duration: 3, // seconds
      request_times: 0,
      transaction: null,
      resendDialog: false,
    }),
    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')
				}
      },
    },
    watch: {
    },
    mounted () {
      window.app = this;
      this.initWhiteLabel();
      
      this.loading_widget.loading=true;
      if (this.getUrlParam('cancelled') == 1) {
        this.rerequest_limits = 1;
      }
      if (this.is_mobile) {
        let _this = this;
        setTimeout(function () {
          _this.getTransaction();
        }, 1300);
      } else {
        this.getTransaction();
      }
    },
    provide () {
      return {
        ...Object.assign(...Object.keys(methods).map(m=>({[m]:methods[m]}))),
        base_uri: this.base_uri,
        session_path: this.session_path,
      }
    },
    methods: {
      ...methods,
      // methods
      initWhiteLabel() {
        this.event = {
          id: localStorage.getItem("eventId"),
          is_white_label: true,
          fields: {
            default: {
              title: localStorage.getItem("brandEventName"),
            }
          },
          settings: {
            white_label_logo: localStorage.getItem("brandLogo"),
            white_label_name: localStorage.getItem("brandName"),
            white_label_color: localStorage.getItem("brandColor"),
            white_label_mode: localStorage.getItem("brandDark"),
          },
          organizer: {
            fields: {
              default: {
                title: localStorage.getItem("brandMerchantName"),
              }
            }
          }
        };
        if (this.event.is_white_label && this.event.settings.white_label_color) {
          this.$vuetify.theme.themes.light.primary = this.event.settings.white_label_color;
          this.$vuetify.theme.themes.dark.primary = this.event.settings.white_label_color;
        }
        if (localStorage.getItem("brandEventName")) {
          document.title = document.title + ' - ' + localStorage.getItem("brandEventName");
        }
      },
      getTransaction(refresh = false) {
        let _this = this;
        if ((this.request_times < this.rerequest_limits)|| refresh) {
          this.loading_widget.loading=true;
          axios.get("<?=$apiEndpoint;?>"+`event_transactions/${this.code}`, {
            headers: {
              'Content-Type': 'application/json',
            }
          }).then(res => {
            this.request_times++;
            this.loading_widget.loading=false;
            if(this.request_times >= this.rerequest_limits) {
              setTimeout(function(){ _this.transaction = res.data.data;}, _this.rerequest_duration * 1000);
            }
            if (res.data.result === 'success') {
              if (res.data.data.status === 'waiting_payment') {
                this.loading_widget.loading=true;
                setTimeout(_this.getTransaction, _this.rerequest_duration * 1000);
              } else {
                this.transaction = res.data.data;
                if (!this.transaction.event_agent_id) {
                  dataLayer.push({
                    'event': 'eec.purchase',
                    'ecommerce': {
                      'purchase': {
                        'actionField': {
                          'id': this.transaction.code,
                          'revenue': this.transaction.payment_price,
                          'coupon': this.transaction.fields.discount_code
                        },
                        'products': this.transaction.grouped_tickets.map(variant => ({
                          'id': this.transaction.event_id,
                          'name': this.transaction.fields.event_title_default,
                          'category':  this.transaction.event_category.fields.default.title, // this.transaction.event_category_id,
                          'brand': this.transaction.fields.organizer_title_default, // 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_default,
                          'quantity': variant.quantity,
                          'price': parseFloat(variant.unit_payment_price)
                        }))
                      }
                    }
                  });
                  fbq('track', 'Purchase', { 
                    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
                  });
                }
              }
            }
          }).catch(err => {
            this.request_times++;
            this.loading_widget.loading=false;
            if (err.status === 404) {
              location.assign(this.session_path+"404");
            } else {
              this.handleError(err);
            }
          });
        } else {
          this.loading_widget.loading=false;
        }
      },
      backToEvent() {
        if (window.location === window.parent.location) {
          var current_params = new URLSearchParams(window.location.search);
          location.assign(this.session_path+"event/"+(this.transaction.fields.event_url_string || this.transaction.event_id)+"?"+current_params.toString());
        } else {
          let event_url = "https://" + this.transaction.fields.event_domain + "/" + this.transaction.fields.event_url_string + "?lang=" + this.$i18n.locale;
          window.open(event_url, '_top');
        }
      },
      openMap(addressName) {
        window.open("https://www.google.com/maps/search/?api=1&query=" + encodeURI(addressName), ' ', 'width=800, height=800')
      },
    }
  });
})();
</script>
</body>
</html>
