<?php
  include_once('settings/index.php');
  error_reporting(0);
  $eid = $_GET['code'];
  $get_url = $apiEndpoint."events/".$eid."?guest_id=$_gid";
  $event_json = @file_get_contents($get_url);
  $event = json_decode($event_json, true)["data"] ?? [];
  $event_name = $event['fields']['default']['title'];
  $event_name = preg_replace("/\"/", "\\\"", $event_name);
  $event_desc = $event['fields']['default']['description'] ?? '';
  if($event_desc){
    $event_desc = preg_replace("/<.*?>/", "", $event_desc);
    $event_desc = preg_replace("/\"/", "\\\"", $event_desc);
    if(strlen($event_desc) > 180){
      $event_desc = substr($event_desc, 0, 150) . "⋯";
    }
  }
  $event_image =$event['fields']['default']['image_url'];
  
  $event_start_date =$event['start_date'];
  $event_end_date =$event['end_date'];
  $event_venue =$event['fields']['default']['venue'];
  $event_venue = preg_replace("/\"/", "\\\"", $event_venue);
  $event_address =$event['fields']['default']['address'];
  $event_address = preg_replace("/\"/", "\\\"", $event_address);
  
  $event_tickets = $event['tickets'] ?? [];

  $organizer_name =$event['organizer']['fields']['default']['title'];
  $organizer_name = preg_replace("/\"/", "\\\"", $organizer_name);
  $organizer_email =$event['organizer']['email'];
  $organizer_phone = preg_replace('/,/','',($event['organizer']['phone']));
  $organizer_logo =$event['organizer']['picture_url'];
  $organizer_url_string =$event['organizer']['url_string'];
?>
<!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><?=$event_name;?></title>
    <link rel="shortcut icon" href="<?=$host_url.$base_uri;?>static/favicon.ico" type="image/x-icon">
    <meta property="og:title" content="<?=$event_name?$event_name:'1TICKS - 活動行銷就係1TICKS咁簡單';?>" />
    <meta name="twitter:title" content="<?=$event_name?$event_name:'1TICKS - 活動行銷就係1TICKS咁簡單';?>" />
    <meta name="description" content="<?=$event_desc?$event_desc:'在1TICKS上創建活動、處理票務及活動行銷比你想像中更容易，由網上宣傳、活動登記、電子門票入場都可以1TICKS過完成！舉辦不收費活動更可免費使用，讓你不費分毫即可將活動達至最大曝光。';?>" />
    <meta property="og:description" content="<?=$event_desc?$event_desc:'在1TICKS上創建活動、處理票務及活動行銷比你想像中更容易，由網上宣傳、活動登記、電子門票入場都可以1TICKS過完成！舉辦不收費活動更可免費使用，讓你不費分毫即可將活動達至最大曝光。';?>" />
    <meta name="twitter:description" content="<?=$event_desc?$event_desc:'在1TICKS上創建活動、處理票務及活動行銷比你想像中更容易，由網上宣傳、活動登記、電子門票入場都可以1TICKS過完成！舉辦不收費活動更可免費使用，讓你不費分毫即可將活動達至最大曝光。';?>" />
    <meta property="og:image" content="<?=$event_image?$event_image:'<?=$host_url.$base_uri;?>static/preview.png';?>" />
    <meta name="twitter:image" content="<?=$event_image?$event_image:'<?=$host_url.$base_uri;?>static/preview.png';?>" />
    <meta property="og:url" content="<?=$host_url.$session_path;?>event/<?=$eid;?>" />
    <script type=application/ld+json>{
      "@context": "https://www.schema.org",
      "@type": "Event",
      "name": "<?=$event_name;?>",
      "image": "<?=$event_image;?>",
      "url": "<?=$host_url.$session_path;?>event/<?=$eid;?>",
      "description": "<?=$event_desc;?>",
      "startDate": "<?=$event_start_date;?>",
      "endDate": "<?=$event_end_date;?>",
      "location": {
        "@type" : "Place",
        "name" : "<?=$event_venue;?>",
        "address" : "<?=$event_address;?>"
      },
      "offers": [
      <?php for($i = 0; $i < count($event_tickets); $i++):?>
        {
          "@type": "Offer",
          "name": "<?=preg_replace("/\"/", "\\\"", $event_tickets[$i]->fields->default->title);?>",
          "price": <?=$event_tickets[$i]->price ?? 0;?>,
          "priceCurrency": "<?=$event_tickets[$i]->currency;?>",
          "url": "<?=$host_url.$session_path;?>event/<?=$eid;?>",
          "availability": "<?=($event_tickets[$i]->remainder>0)?'http://schema.org/InStock':'https://schema.org/SoldOut';?>",
          "priceValidUntil": "<?=!empty($event_tickets[$i]->active_end_date)?$event_tickets[$i]->active_end_date:$event_end_date;?>",
          "validFrom": "<?=!empty($event_tickets[$i]->active_start_date)?$event_tickets[$i]->active_start_date:$event_start_date;?>"
        }
        <?php if($i<(count($event_tickets)-1)):?>,<?php endif;?>
      <?php endfor;?>
      ],
      "organizer": {
        "@type": "Organization",
        "name": "<?=$organizer_name;?>",
        "email": "<?=$organizer_email;?>",
        "phone": "<?=$organizer_phone;?>",
        "logo": "<?=$organizer_logo;?>",
        "url": "<?=$host_url.$session_path;?>organizer/<?=$organizer_url_string;?>"
      }
    }</script>
    <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>
    <app-toolbar :is_whitelabel="_get(event,'is_white_label',false)" :settings="_get(event,'settings',{})"></app-toolbar>
    <v-main>
      <div class="page-wrapper">
        <v-container class="pa-0" fluid v-cloak>
          <section>
            <v-row no-gutters>
              <v-col cols="12" lg="8" offset-lg="2">
                <v-card :flat="$vuetify.breakpoint.xsOnly">
                  <blur-image :src="_f(event.fields, 'image_url')" alt="event banner" :ratio="$vuetify.breakpoint.mdAndUp?3:1.91" :contain="$vuetify.breakpoint.mdAndUp?true:false"></blur-image>
                  <v-divider></v-divider>
                  <!-- title and share button -->
                  <v-card-title id="event-title" class="py-2">
                    <v-row dense align="center">
                      <v-col>
                        <h1 :class="'font-weight-bold '+($vuetify.breakpoint.mdAndUp?'headline':'title')">{{_f(event.fields, 'title')}}</h1>
                      </v-col>
                      <v-col cols="auto">
                        <share-options 
                          flat 
                          icon 
                          color="primary" 
                          :is_mobile="is_mobile" 
                          :event_fields="event.fields" 
                          :url="getEventURL(event)"
                        ></share-options>
                      </v-col>
                    </v-row>
                  </v-card-title>
                  <!-- event basic info -->
                  <v-divider></v-divider>
                  <v-card-text id="event-basic-info">
                    <event-basic-info :event="event"></event-basic-info>
                  </v-card-text>
                  <!-- event tickets -->
                  <v-divider v-if="event.tickets.length > 0"></v-divider>
                  <v-card-text id="event-tickets" class="black--text" v-if="event.tickets.length > 0">
                    <event-tickets :event="event"></event-tickets>
                  </v-card-text>
                  <!-- event description -->
                  <v-divider v-if="_get(event, 'fields.default.description.length',0)>0"></v-divider>
                  <v-card-text id="event-description" v-if="_get(event, 'fields.default.description.length',0)>0">
                    <v-row dense align="center">
                      <v-col cols="auto">
                        <v-icon large>mdi-calendar-text</v-icon>
                      </v-col>
                      <v-col>
                        <h3 class="title">{{$t('event.details')}}</h3>
                      </v-col>
                    </v-row>
                    <p class='description ql-editor pa-0 black--text' v-html="changeLinkColor(_f(event.fields, 'description'))"></p>
                  </v-card-text>
                  <!-- event organizer (white label) -->
                  <v-divider v-if="event.is_white_label"></v-divider>
                  <v-card-text id="event-organizer" v-if="event.is_white_label">
                    <v-row dense align="center">
                      <v-col cols="auto">
                        <v-icon large>mdi-domain</v-icon>
                      </v-col>
                      <v-col>
                        <h3 class="title">{{$t('event.organizer')}}</h3>
                      </v-col>
                    </v-row>
                    <v-row dense>
                      <v-col class="text-center">
                        <v-avatar size="100" color="primary">
                          <v-img v-if="event.organizer.picture_url && event.organizer.picture_url!='null'" aspect-ratio="1" :src="event.organizer.picture_url" :alt="event.settings.white_label_name"></v-img>
                          <span v-else class="display-3" :class="(event.settings.white_label_mode=='dark')?'white--text':'black--text'">{{event.settings.white_label_name.substr(0,1).toUpperCase()}}</span>
                        </v-avatar>
                        <div class="mt-3 title font-weight-bold">{{ _f(event.organizer.fields, 'title') }}</div>
                      </v-col>
                    </v-row>
                    <v-row dense justify="center">
                      <v-col cols="12" md="auto" class="py-1" :class="{'xs12':$vuetify.breakpoint.smAndDown}" v-if="event.organizer.phone.replace(',', '')!=''">
                        <v-icon small class="mr-1">mdi-phone</v-icon><a :href="'tel:'+event.organizer.phone.replace(',', '')" class="font-weight-bold">{{ event.organizer.phone.replace(',', '') }}</a>
                      </v-col>
                      <v-col cols="12" md="auto" class="py-1" :class="{'xs12':$vuetify.breakpoint.smAndDown}" v-if="event.organizer.email">
                        <v-icon small class="mr-1">mdi-email</v-icon><a :href="'mailto:'+event.organizer.email" class="font-weight-bold">{{ event.organizer.email }}</a>
                      </v-col>
                      <v-col cols="12" md="auto" class="py-1" :class="{'xs12':$vuetify.breakpoint.smAndDown}" v-if="event.organizer.website_url">
                        <v-icon small class="mr-1">mdi-web</v-icon><a :href="event.organizer.website_url" target="_blank" class="font-weight-bold">{{ event.organizer.website_url }}</a>
                      </v-col>
                    </v-row>
                    <v-row dense justify="center">
                      <v-col>
                        <p class='description ql-editor' v-html="_f(event.organizer.fields, 'description')"></p>
                      </v-col>
                    </v-row>
                  </v-card-text>
                </v-card>
              </v-col>
            </v-row>
          </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/general/blurImage.vue"); ?>
  <?php include("components/event/eventBasicInfo.vue"); ?>
  <?php include("components/event/eventTickets.vue"); ?>
  <?php include("components/shareOptions.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
      event: <?=json_encode($event);?>,
    }),
    computed: {
    },
    watch: {
    },
    mounted () {
      window.app = this;

      this.applyEventSettings();
      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;
      }
    },
    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
      applyEventSettings () {
        if (this.event) {
          if (this.event.is_white_label) {
            localStorage.setItem("isInWhiteLabel", "true");
            localStorage.setItem("eventId",this._get(this.event, 'id', ''));
            localStorage.setItem("brandLogo",this._get(this.event, 'settings.white_label_logo', ''));
            localStorage.setItem("brandName",this._get(this.event, 'settings.white_label_name', ''));
            localStorage.setItem("brandColor",this._get(this.event, 'settings.white_label_color', '#ff5000'));
            localStorage.setItem("brandDark",this._get(this.event, 'settings.white_label_mode', 'dark'));
            localStorage.setItem("brandEventName", this._get(this.event, 'fields.default.title', ''));
            localStorage.setItem("brandMerchantName",this._get(this.event, 'organizer.fields.default.title', ''));

            document.title = this._get(this.event, 'fields.default.title', '') + " - " +this._get(this.event, 'organizer.fields.default.title', '');
          } else {
            this.$root.$emit('CLEAR_WHITE_LABEL');
            document.title = "1TICKS | " + this._get(this.event, 'fields.default.title', '') + " - " + this._get(this.event, 'organizer.fields.default.title', '');
          }
        }
      },
      getEvent(id) {
        this.loading_widget.loading=true;
        let query = this.params({
          log_view: true,
          url_params: this.getQuery(),
        });
        axios.get("<?=$apiEndpoint;?>"+`events/${id}?${query}`, {
          headers: {
            'Content-Type': 'multipart/form-data',
          }
        }).then(res => {
          this.event = res.data.data;
          this.applyEventSettings();
          // init purchase quantity to 0
          this.event.tickets = this.event.tickets.map(ticket => ({...ticket, purchase_quantity: 0 }));
          dataLayer.push({
            'event': 'eec.detail',
            'ecommerce': {
              'detail': {
                'products': [{
                  'id': this.event.id,
                  'name': this.event.fields.default.title,
                  'category': this.event.event_category.fields.default.title, // this.event.event_category_id,
                  'brand': this.event.organizer.fields.default.title, // this.event.organizer_id,
                  'event_tag': this.event.tags.join(',') ? this.event.tags.join(',') + ',' : ''
                }]
              }
            }
          });
          
          let _this = this;
          setTimeout(function() {
            fbq('track', 'ViewContent', { 
              env: "<?=$env;?>",
              event_id: _this.event.id,
              event_tag: _this.event.tags.join(',') ? _this.event.tags.join(',') + ',' : '',
              event_category_id: _this.event.event_category_id,
              event_country_id: _this.event.country_id,
            });
          }, 3000);
          
        }).catch(err => {
          if (err.status === 404) {
            location.assign(this.session_path+"404");
          } else {
            this.handleError(err);
          }
        }).finally(()=> {
          this.loading_widget.loading = false;
        });
      },
      getEventURL(event) {
        if (window.location === window.parent.location) {
          return location.origin + location.pathname;
        } else {
          return document.referrer;
        }
      },
      checkStatus (ticket) {
        return 'available';
      },
      changeLinkColor(html) {
        return this.event.is_white_label ? html.replace(/<a /g, "<a style=\"color: " + this.event.settings.white_label_color + "\" ") : html
      },
    }
  });
})();
</script>
</body>
</html>
