<?php include("components/event/eventTicketItems.vue"); ?>
Vue.component('event-tickets', {
  props: { 
    event: {
      type: Object,
    },
  },
  inject: ['_f','_get','session_path','handleError'],
  data: ()=>({
    loading: false,
    submitted: false,
  }),
  computed: {
    eventGroupIds() {
      return this.event.tickets.map(o=>o.event_ticket_group_id).filter((val, i, self) => (val && val!='' && self.indexOf(val)===i));
    },
    transaction_tickets () {
      return this.event.tickets.filter(t=>t.purchase_quantity>0);
    },
    transaction_quantity () {
      return this.transaction_tickets.reduce((a,b)=>(a+(b.purchase_quantity)),0);
    },
    transaction_amount () {
      return this.transaction_tickets.reduce((a,b)=>(a+(b.price+b.user_fee)*b.purchase_quantity),0);
    },
  },
  mounted () {
  },
  methods: {
    checkTicketStatus(ticket) {
      var ticket_start_sold_at = (ticket.active_start_at && new Date(ticket.active_start_at));
      var event_end_at = (this.event.end_at && new Date(this.event.end_at));
      var ticket_end_sold_at = (ticket.active_end_at && new Date(ticket.active_end_at));
      ticket_end_sold_at = ticket_end_sold_at || event_end_at;
      if (event_end_at && (ticket_end_sold_at > event_end_at)) {
        ticket_end_sold_at = event_end_at;
      }
      if (ticket_start_sold_at >= new Date()) {
        // non started selling
        return "await";
      } else if(ticket_end_sold_at <= new Date()) {
        // ended selling
        return "expired";
      } else if ((ticket.sold+ticket.hold) >= ticket.quantity) {
        // sold out
        return 'soldOut';
      } else {
        // available
        return 'available';
      }
    },
    isPaidEvent() {
      return (this.event.tickets && this.event.tickets.length>0 && this.event.tickets.filter(t=>t.price>0).length>0);
    },
    nextStep() {
      this.submitted = true
      if (this.transaction_tickets.length>0) {
        if(this.$refs.tickets.validate()){
          this.loading = true;
          this.createOrder();
        } else {
          this.$toasted.show(this.$t('toast.form.noTickets'), {
            theme: 'primary',
            type: 'info',
            position: 'bottom-right',
            icon: 'close',
            duration: 5000
          });
        }
      } else {
        this.$vuetify.goTo(this.$refs.tickets);
      };
    },
    createOrder() {
      var tickets = [];
      this.transaction_tickets.map(t=>({event_ticket_id: t.id, purchase_quantity: t.purchase_quantity})).forEach(t=>{
        for (var count = 0; count < t.purchase_quantity; count++) {
          tickets.push({
            event_ticket_id: t.event_ticket_id
          });
        }
      });
      var data = {
        event_id: this.event.id,
        status: "hold",
        currency: this.event.currency,
        price: this.transaction_tickets.reduce((a,b)=>(a+(b.price)*b.purchase_quantity),0),
        user_fee: this.transaction_tickets.reduce((a,b)=>(a+(b.user_fee)*b.purchase_quantity),0),
        organizer_fee: this.transaction_tickets.reduce((a,b)=>(a+(b.organizer_fee)*b.purchase_quantity),0),
        payment_price: this.transaction_amount,
        tickets: tickets,
        
        locale: i18n.locale,
        user_created_at: new Date(),
      };
      axios.post("<?=$apiEndpoint;?>"+`event_transactions`, data, {
        headers: {
          'Content-Type': 'application/json',
        }
      }).then(res => {
        dataLayer.push({
          'event': 'addToCart',
          'ecommerce': {
            'currencyCode': this.event.currency,
            'add': {
              'products': this.event.tickets.filter(ticket => (ticket.purchase_quantity > 0)).map(variant => ({
                '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(',') + ',' : '',
                'variant_id': variant.event_ticket_id,
                'variant': variant.fields.default.title,
                'quantity': variant.purchase_quantity,
                'price': parseFloat(variant.price) + parseFloat(variant.user_fee)
              }))
            }
          }
        });
        fbq('track', 'AddToCart', { 
          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,
          currency: this.event.currency,
          value: parseFloat(this.transaction_amount)
        });

        var current_params = new URLSearchParams(window.location.search);
        location.assign(this.session_path+"checkout/"+res.data.data.token+"?"+current_params.toString());
        
        this.loading = false;
      }).catch(err => {
        this.loading = false;
        this.handleError(err);
      })
    },
    checkQuantity(ticket) {
      if (ticket.purchase_quantity>ticket.remainder) {
        ticket.purchase_quantity = ticket.remainder;
        this.$toasted.show(this.$t('warning.ticket.remainder'), {
          theme: 'primary',
          type: 'warning',
          position: 'bottom-right',
          icon: 'warning',
          duration: 5000
        });
      }
    }
  },
  template:
`<div>
  <v-row dense align="center">
    <v-col cols="auto">
      <v-icon large>mdi-ticket</v-icon>
    </v-col>
    <v-col>
      <h3 class="title">{{(isPaidEvent())?$t('ticket.paid.title'):$t('ticket.free.title')}}</h3>
    </v-col>
  </v-row>
  <v-form ref="tickets" class="event-order">
    <!-- group tickets -->
    <v-expansion-panels flat>
      <v-expansion-panel class="no-padding" v-for="group_id in eventGroupIds" :key="group_id">
        <v-sheet 
          rounded 
          elevation="2" 
          class="mb-2"
          style="position: sticky; top: 40px; background-color: white; z-index: 1;"
        >
          <v-expansion-panel-header class="px-3 font-weight-bold">
              {{_f((event.ticket_groups.filter(g=>g.id == group_id)[0]||{}).fields, 'title')}}
            </v-expansion-panel-header>
        </v-sheet>
        <v-expansion-panel-content>
          <div>
            <event-ticket-items
              :tickets="event.tickets.filter(t=>(t.event_ticket_group_id==group_id))"
              :settings="_get(event,'settings',{})"
              :end_at="event.end_at"
            ></event-ticket-items>
          </div>
        </v-expansion-panel-content>
      </v-expansion-panel>
    </v-expansion-panels>

    <!-- single ticket -->
    <div>
      <event-ticket-items
        :tickets="event.tickets.filter(t=>!eventGroupIds.includes(t.event_ticket_group_id))"
        :settings="_get(event,'settings',{})"
        :end_at="event.end_at"
      ></event-ticket-items>
    </div>

    <!-- bottom button -->
    <div 
      class="py-1" 
      ref="bottom_button" 
      :style="$vuetify.breakpoint.smAndDown?'position: fixed; z-index:1; left:0; bottom:0; width: 100%; background: white; box-shadow: 0 3px 1px -2px rgba(0,0,0,.2), 0 2px 2px 0 rgba(0,0,0,.14), 0 1px 5px 0 rgba(0,0,0,.12);':''"
    >
      <v-row no-gutters :class="$vuetify.breakpoint.smAndDown?'px-4':'px-3'" align="center" justify="end">
        <v-col v-if="transaction_tickets.length>0">
          <span class="subtitle-1" v-if="transaction_amount>0">{{$t('event.totalLabel')}}</span>
          <span class="subtitle-1 font-weight-bold" v-if="transaction_amount>0">{{event.currency}}{{transaction_amount}}</span>
          <span class="caption">{{$t('event.ticket_selected',{count:transaction_quantity})}}</span>
        </v-col>
        <v-col cols="auto">
          <v-btn @click='nextStep' :loading="loading" color="primary" v-if="isPaidEvent()">{{transaction_tickets.length?$t('event.checkoutButton'):$t('event.ticket')}}</v-btn>
          <v-btn @click='nextStep' :loading="loading" color="primary" v-else>{{transaction_tickets.length?$t('event.registerButton'):$t('event.register')}}</v-btn>
        </v-col>
      </v-row>
    </div>

  </v-form>
</div>`
});