<?php include("components/event/eventBasicInfo.vue"); ?>
<?php include("components/checkout/eventFormQuestions.vue"); ?>
Vue.component('event-form', {
  props: ['transaction','goback','confirm_order'],
  inject: ['_f','_get','validate','session_path','handleError','generateUUID'],
  data: () => ({
    is_agree: null,
    user_area_code: null,
    user_phone: null,
    loading: false,
    badmailList: [
    ],
    files: {},
    upload_errors: {
      show_required: {},
      display: {},
      messages: {},
    },
    allow_file_types: [
      'image/jpg', 
      'image/jpeg', 
      'image/png', 
      'image/gif', 
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',  // docx
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',  // pptx
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',  // xlsx
      'application/pdf',
      'text/csv', 
      'application/x-iwork-keynote-sffkey', 
      'application/x-iwork-numbers-sffnumbers', 
      'application/x-iwork-pages-sffpages', 
      'application/msword', 
      'application/vnd.ms-powerpoint',
      'application/vnd.ms-excel',
      'audio/mpeg',
      'audio/mp4',
      'audio/wav',
      'audio/x-wav',
      'audio/x-ms-wma',
      'application/vnd.rar',
      'application/x-rar',
      'application/x-rar-compressed',
      'application/zip',
      'application/zip-compressed',
      'application/x-zip-compressed',
      'multipart/x-zip',
      'application/x-7z-compressed',
    ],
    submitted: false,
    termsDialog: {
      visible: false,
      type: "terms",
    },
  }),
  computed: {
    area_codes() {
      return [
        { value: '+853', text: '+853' },
        { value: '+852', text: '+852' },
        { value: '+86', text: '+86' },
        { value: '+886', text: '+886' },
        { value: '+', text: '('+this.$t('general.others')+')' },
      ];
    },
    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.form=this;
  },
  methods: {
    nextStep() {
      this.submitted = true;
      this.loading = true;
      let validations = [
        this.$refs.contact.validate(),
      ];
      // if has form, validate all forms
      if ( this.transaction.tickets.filter(t=>t.event_form).length > 0) {
        validations = validations.concat(this.$refs.questions.map((questions, i)=> {
          return this.$refs.questions[i].$refs.form.validate();
        }));
      }

      if (!validations.includes(false)) {
        this.tryUploadImageAndSaveEvent();
      } else {
        let _this = this;
        this.transaction.tickets.forEach( function(ticket, t_index){
          if (typeof ticket.event_form != 'undefined') {
            ticket.event_form.inputs.forEach( function(question, q_index){
              let imageId = ticket.id + '_'  + q_index
              if (question.type == "file") {
                if (question.is_required && !_this.files.hasOwnProperty(imageId) && question.answer == null) {
                  _this.upload_errors.show_required[imageId] = true
                  _this.upload_errors.show_required = {
                    ..._this.upload_errors.show_required,
                    [imageId]: true,
                  }
                  _this.$forceUpdate()
                }
              }
            })
          }
        });
        this.loading = false;
        this.$root.showToast({text: this.$t('form.invalid'), zindex:301}, "warning");
        var first_invalid_el = (this.$refs.contact.$children).concat(
          ...Object.values(this.$refs.contact.$children).map(c=>Object.values(c.$children)),
          ...[].concat(...this.$refs.questions.map(t=>Object.values(t.$refs.form.$children)))
        ).filter(input=>Array.isArray(input.errorBucket) && (input.errorBucket.length>0))[0];
        first_invalid_el && first_invalid_el.$el.scrollIntoView({behavior: "smooth", block: "center"});
      }
    },
    tryUploadImageAndSaveEvent() {  
      let _this = this
      _this.loading = true
      let allValid = true
      this.transaction.tickets.forEach( function(ticket, t_index){
        if (typeof ticket.event_form != 'undefined') {
          ticket.event_form.inputs.forEach( function(question, q_index){
            let imageId = ticket.id + '_'  + q_index
            if (question.type == "file") {
              if (question.is_required && !_this.files.hasOwnProperty(imageId) && (question.answer == null)) {
                _this.upload_errors.show_required[imageId] = true
                _this.upload_errors.show_required = {
                  ..._this.upload_errors.show_required,
                  [imageId]: true,
                }
                _this.$forceUpdate()
                allValid = false
                _this.$root.showToast({text: this.$t('form.invalid'), zindex:301}, "warning");
                _this.loading = false
              } else if (_this.files.hasOwnProperty(imageId)) {
                let formData = new FormData();
                formData.append('files[]', _this.files[imageId]);
                const merchant_id = sessionStorage.getItem('_oi');
                let mid = merchant_id ? merchant_id.padStart(4, '0') : '0000';
                let image_uuid = _this.generateUUID();
                formData.append('uuid[]', mid + '-' + image_uuid);
                formData.append('no_compress', true);
                formData.append('dir', 'forms/'); 
                formData.append('path',"<?=$upload_path;?>");
                let _question = question
                axois.post("<?=$upload_php;?>", formData, {
                  headers: {
                    'Content-Type': 'multipart/form-data',
                  }
                }).then( (data) => {
                  if (data.data.data.length > 0) {
                    _question.answer = "<?=$upload_host;?>"+ '/' + data.data.data[0].url;
                    delete _this.files[imageId]
                    if (Object.keys(_this.files).length == 0 && allValid) {
                      _this.loading = false
                      _this.confirm_order();
                    }
                  } else {
                    _this.upload_errors.messages[imageId] = files[imageId].name
                    allValid = false
                    _this.$root.showToast({text: this.$t('form.invalid'), zindex:301}, "warning");
                  }
                });
              }
            } else if (question.is_shown_extra) {
              if (question.answer && question.answer.includes('__other')) {
                if(Array.isArray(question.answer)){
                  question.answer[question.answer.indexOf("__other")] = "__other:"+question.answer_extra
                } else {
                  question.answer = "__other:"+question.answer_extra
                }
              }
            }
          })
        } 
      })
      if (Object.keys(_this.files).length == 0 && allValid) {
        _this.confirm_order();
      }
    },
    
    openMap(addressName) {
      this.open("https://www.google.com/maps/search/?api=1&query=" + encodeURI(addressName), ' ', 'width=800, height=800')
    },
    openTerms() {
      this.termsDialog = {
        visible: true,
        type: "terms",
      };
    },
    openPrivacy() {
      this.termsDialog = {
        visible: true,
        type: "privacy",
      };
    },
    processFile (id, event) {
      this.upload_errors.display[id] = false;
      this.upload_errors.messages[id] = [];
      let file = event.target.files[0];
      if (file) {
        if(!file.type) {
          var ext = file.name.split('.').pop();
          if (ext === 'xls') {
            Object.defineProperty(file, 'type', {value: 'application/vnd.ms-excel'});
          }
        }
        if (this.allow_file_types.indexOf(file.type) === -1) {
          this.upload_errors.display[id] = true;
          this.upload_errors.messages[id] = this.$t('error.file.format', { file: file.name })
        } else if (file.size > 5 * 1024 * 1024) {
          this.upload_errors.display[id] = true;
          this.upload_errors.messages[id] = this.$t('error.file.size', { file: file.name })
        } else {
          this.upload_errors.show_required[id] = false;
          this.$el.querySelector('#image_name_' + id).innerHTML = file.name;
          file.url = URL.createObjectURL(file);
          this.$el.querySelector('#image_preview_' + id).innerHTML = '<img src="'+file.url+'" />';
          this.files[id] = file;
        }
        this.$refs.questions.forEach((question, i)=> {
          return this.$refs.questions[i].$forceUpdate();
        });
        this.$forceUpdate()
      }
    },
  },
  template:
`<v-form ref="contact" class="event-order">
  <v-row no-gutters>
    <v-col cols="12" lg="8" offset-lg="2" v-if="transaction">
      <!-- event info -->
      <v-card>
        <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>
        <v-card-text>
          <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_id: transaction.organizer_id,
              organizer: transaction.organizer
            }" :isInWhiteLabel="isInWhiteLabel" :whiteLabel="whiteLabel"></event-basic-info>
        </v-card-text>
      </v-card>
      <!-- buyer info -->
      <v-card class="my-3 border-width-1px">
        <v-card-title>
          <h4 class='title primary--text'>1. {{$t('event.confirm.fillInfo')}}</h4>
        </v-card-title>
        <v-divider></v-divider>
        <v-card-text class="pb-0">
          <!-- <h4 class="title font-weight-light mb-3">{{$t('event.confirm.contactInfo')}}</h4> -->
          <v-row dense>
            <!-- username -->
            <v-col cols="12" lg="6">
              <v-row dense>
                <v-col cols="6">
                  <v-text-field
                    autocomplete="fimily-name"
                    prepend-inner-icon="mdi-account" 
                    v-model="transaction.user_last_name" 
                    :label="$t('input.lastName.label')"
                    :rules="[
                      v=>(!!v) || $t('validation.required',{field: $t('input.lastName.label')}),
                    ]"
                    :hide-details="submitted?'auto':true"
                    outlined 
                    required
                    tabindex="1"
                  ></v-text-field>
                </v-col>
                <v-col cols="6">
                  <v-text-field 
                    autocomplete="given-name"
                    prepend-inner-icon="mdi-account" 
                    v-model="transaction.user_first_name" 
                    :label="$t('input.firstName.label')"
                    :rules="[
                      v=>(!!v) || $t('validation.required',{field: $t('input.firstName.label')}),
                    ]"
                    :hide-details="submitted?'auto':true"
                    outlined
                    required
                    tabindex="1"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <!-- phone -->
            <v-col cols="12" lg="6">
              <v-row dense>
                <v-col cols="5">
                  <v-select 
                    prepend-inner-icon="mdi-cellphone" 
                    v-model="user_area_code"
                    :label="$t('input.area_code.label')"
                    :rules="[
                      v=>(!!v) || $t('validation.required',{field: $t('input.area_code.label')}),
                    ]"
                    :hide-details="submitted?'auto':true"
                    :items="area_codes"
                    @change="transaction.user_phone = user_area_code + ',' + user_phone"
                    outlined 
                    single-line
                    :tabindex="isInWhiteLabel?2:1"
                  ></v-select>
                </v-col>
                <v-col cols="7">
                  <v-text-field 
                    autocomplete="tel-local"
                    v-model="user_phone" 
                    :label="$t('input.phone.label')"
                    :rules="[
                      v=>(!!v) || $t('validation.required',{field: $t('input.phone.label')}),
                      v=>(!v || /^[0-9]{2,}$/.test(v)) || $t('validation.numeric',{field: $t('input.phone.label')}),
                      v=>(!v || v.length>=5) || $t('validation.min',{field: $t('input.phone.label'),min:5}),
                      v=>(!v || v.length<=16) || $t('validation.max',{field: $t('input.phone.label'),max:16}),
                    ]"
                    :hide-details="submitted?'auto':true"
                    @change="transaction.user_phone = user_area_code + ',' + user_phone"
                    type="tel"
                    outlined 
                    single-line
                    :tabindex="isInWhiteLabel?2:1"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <!-- email -->
            <v-col cols="12" :lg="isInWhiteLabel?6:12">
              <v-row dense>
                <v-col cols="12">
                  <v-text-field 
                    autocomplete="email"
                    prepend-inner-icon="mdi-email" 
                    v-model="transaction.user_email" 
                    :label="$t('input.email.label')"
                    :rules="[
                      v=>(!!v) || $t('validation.required',{field: $t('input.email.label')}),
                      v => validate('email', v) || $t('validation.email', {field:$t('input.email.label')}),
                      v => validate('email_characters', v) || $t('validation.email_characters', {field:$t('input.email.label')}),
                    ]"
                    type="email"
                    ref="email"
                    outlined
                    persistent-hint
                    :hint="$t('input.email.receiveEmailHint')"
                    required
                    :tabindex="isInWhiteLabel?3:1"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-col>
            <!-- confirm email -->
            <v-col cols="12" lg="6" v-if="isInWhiteLabel">
              <v-row dense>
                <v-col cols="12">
                  <v-text-field 
                    @paste.prevent
                    prepend-inner-icon="mdi-email" 
                    v-model="transaction.user_email_confirmation" 
                    :placeholder="$t('input.confirm_email.placeholder')"
                    :label="$t('input.confirm_email.label')"
                    :rules="[
                      v=>(!!v) || $t('validation.required',{field: $t('input.confirm_email.label')}),
                      v => validate('email', v) || $t('validation.email', {field:$t('input.confirm_email.label')}),
                      v => validate('email_characters', v) || $t('validation.email_characters', {field:$t('input.confirm_email.label')}),
                      v => (v==transaction.user_email) || $t('validation.confirm', {field:$t('input.confirm_email.label'),confirm:$t('input.email.label')}),
                    ]"
                    :hide-details="submitted?'auto':true"
                    type="email"
                    outlined
                    required
                    :tabindex="isInWhiteLabel?3:1"
                  ></v-text-field>
                </v-col>
              </v-row>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
      <!-- ticket forms -->
      <v-card class='mt-3 border-width-1px' v-if="transaction.tickets.filter(t=>t.event_form).length > 0">
        <v-card-title>
          <h4 class='title primary--text'>2. {{$t('event.confirm.fillForm')}}</h4>
        </v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-row no-gutters>
            <v-col cols="12" v-for="(ticket, t_index) in transaction.tickets.filter(t=>t.event_form)" :key="t_index">
              <v-row my-0 v-if="t_index > 0">
                <v-divider class="mb-2"></v-divider>
              </v-row>
              <v-chip color="primary" class="auto-height font-weight-bold" :dark="isInWhiteLabel ? (whiteLabel.white_label_mode == 'dark') : true">{{ (t_index+1)+'. '+ticket.fields.event_ticket_title }}</v-chip>
              <div class="mt-2">
                <event-form-questions 
                  ref="questions"
                  :questions="ticket.event_form.inputs" 
                  :submitted="submitted" 
                  :ticket_id="ticket.id"
                  :upload_errors="upload_errors"
                  :processFile="processFile"
                  :sticky_top="40"
                  :allow_file_types="allow_file_types"
                ></event-form-questions>
              </div>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
      <v-row dense justify-center>
        <!-- agree t&c and privacy policy -->
        <v-col cols="12" py-1>
          <v-checkbox 
            color="primary" 
            v-model="is_agree"
            :rules="[
              v=>(!!v) || $t('validation.required',{field: $t('input.agree.label')}),
            ]"
            :hide-details="submitted?'auto':true"
            @change="is_agree?'':(is_agree = null)"
            required
          >
            <template v-slot:label>
              <div>
                {{$t('event.confirm.agreement1')}}<span @click="openTerms" class="primary--text">{{$t('Doc.termsOfUse')}}</span>{{$t('event.confirm.agreement2')}}<span @click="openPrivacy" class="primary--text">{{$t('Doc.privacyPolicy')}}</span>
              </div>
            </template>
          </v-checkbox>
        </v-col>
        <!-- next button -->
        <v-col lg4 cols="12" pt-0>
          <v-btn class="ma-0" color="primary" :style="(isInWhiteLabel && whiteLabel.white_label_mode == 'light') ? 'color: black' : 'color: white'" @click="nextStep" :loading="loading" block>{{$t('event.confirm.checkout')}}</v-btn>
        </v-col>
      </v-row>
    </v-col>
  </v-row>
  <v-dialog
    fullscreen 
    hide-overlay 
    transition="dialog-bottom-transition"
    v-model="termsDialog.visible"
  >
    <v-card color="white">
      <v-card-title dark color="primary" class="pa-0">
        <v-card color="primary" width="100%">
          <v-row justify-end>
            <v-btn icon dark @keypress.prevent @click="termsDialog.visible = false;">
              <v-icon>mdi-close</v-icon>
            </v-btn>
          </v-row>
        </v-card>
      </v-card-title>
      <v-card-text>
        <terms v-if="termsDialog.type == 'terms'"></terms>
        <privacy v-if="termsDialog.type == 'privacy'"></privacy>
      </v-card-text>
    </v-card>
  </v-dialog>
</v-form>`
});