<template>
  <div class="card mb-2">
    <header class="card-header">
      <h5 class="mb-0">Vouchercode controleren</h5>
    </header>
    <div class="card-body">
      <form @submit.prevent="submit">
        <input type="hidden" name="actionId" :value="this.actionId">

        <field label="Vouchercode">
          <input type="text" name="code" required class="form-control form-control-integer mb-3" />
          <span class="alert alert-secondary mb-3" role="alert" v-if="message">{{message}}</span>
        </field>

        <field class="mb-0" no-focus>
          <button type="submit" class="btn btn-primary" :disabled="isLoading" v-text="isLoading ? 'Voucher aan het controleren...' : 'Valideer vouchercode'"></button>
        </field>
      </form>
    </div>
  </div>
</template>

<script>
import { handleFetch } from '../api/helpers';
import field from '../shared/form/field.vue';

export default {
  props: {
    actionId: {
      type: String,
      required: true,
    },
    verifyUrl: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      isLoading: false,
      message: ''
    };
  },
  methods: {
    async submit(e) {
      try {
        this.message = '';
        this.isLoading = true;

        const response = await handleFetch(this.verifyUrl, {
          method: 'post',
          body: new FormData(e.target),
          credentials: 'include',
        }, false);

        this.message = await response.text();

      } catch (e) {
        this.message = 'Er ging iets mis bij het controleren van de code';
      } finally {
        this.isLoading = false;
      }
    }
  },
  components: {
    field
  }
}
</script>
