<template>
  <div v-if="newsletter_status" class="content-box">

      <base-alert
        v-show="alert.type"
        :apperance="alert.type"
        @close="alert = {}"
      >
        <span v-html="alert.message"></span>
      </base-alert>

      <validation-observer
        ref="validationObserver"
        tag="div"
        v-slot="{ handleSubmit, invalid }"
        @submit.prevent="onValidationObserverSubmit()"
      >
        <form
          method="post" 
          action="."
          ref="form"
          autocomplete="on"
          @submit.prevent="handleSubmit(onSubmit)"
        >
          <div class="content-box col-xs-12 col-md-12 no-padding">

            <div class="title-style">
              <span class="footer-title text-small visible-block"> 
                <strong>Newsletter</strong>
              </span>
            </div>

            <p class="text-small visible-block vertical-margin-x-small">Cadastre-se abaixo e receba nossas novidades com exclusividade por e-mail:</p>

            <div v-if="enableNewsletterName" class="flex vertical-margin-x-small">
              <validation-provider
                name="newsletter_name"
                rules="required|min: 3"
                class="right-padding-x-small field-style"
                v-slot="{ errors, valid, passed}"
              >
                <base-input
                  name="newsletter_name"
                  mask="alphanumeric"
                  maxlength="70"
                  required
                  type="no-field-entry"
                  placeholder="Digite seu nome"
                  v-model="newsletter_name"
                  :valid="valid && passed"
                  :error="errors[0]"
                >
                </base-input>
              </validation-provider>

              <validation-provider
                name="newsletter_email"
                rules="email|required|min: 3"
                class="left-padding-x-small field-style"
                v-slot="{ errors, valid, passed}"
              >
                <base-input
                  name="newsletter_email"
                  mask="alphanumeric"
                  maxlength="96"
                  required
                  type="no-field-entry"
                  placeholder="Digite seu e-mail"
                  v-model="newsletter_email"
                  :valid="valid && passed"
                  :error="errors[0]"
                  @focusout="validateEmail"
                >
                </base-input>
              </validation-provider>
            </div>                

            <div v-else class="vertical-margin-x-small field-style--email">
              <validation-provider
                name="newsletter_email"
                rules="email|required|min: 3"
                v-slot="{ errors, valid, passed}"
              >
                <base-input
                  name="newsletter_email"
                  mask="alphanumeric"
                  maxlength="96"
                  required
                  type="no-field-entry"
                  placeholder="Digite seu e-mail"
                  v-model="newsletter_email"
                  :valid="valid && passed"
                  :error="errors[0]"
                  @focusout="validateEmail"
                >
                </base-input>
              </validation-provider>
            </div> 

            <button 
              type="submit" 
              class="button__newsletter text-small pointer"  
              title="Inscrever-se"
            >
              <a class="text-decoration-none">
                <span>Clique aqui para </span>
                <strong>Inscrever-se</strong>
              </a>
            </button>
            
          </div>
        </form>
      </validation-observer>   

  </div>
</template>

<script>
import axiosApi, {param} from "@assets/js/axios-api";
import formMixin from "@mixins/formMixin";

const BASE_URL = document.getElementById('base-urls').dataset.baseUrlLoja;

export default {
  name: 'TheNewsletter',
  mixins: [formMixin],
  data() {
    return {
      enableNewsletterName: null,
      newsletter_status: null,
      newsletter_email: null,
      newsletter_name: null,
    }
  },
  methods: {
    async onSubmit() {
      await axiosApi({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        method: 'POST',
        url: BASE_URL + '/index.php?route=common/module_newsletter/validateSubscribe',
        data: param({newsletter_email: this.newsletter_email, newsletter_name: this.newsletter_name}),
      })
        .then(({ data }) => {

          if (data.errors) {
            this.$refs.validationObserver.setErrors(data.errors);
            this.alert = {
              type: 'error',
              message: 'Alguns campos estão incorretos. Corrija os campos em vermelho.',
            };
          }
          if (data.success) {
            this.$refs.validationObserver.reset();
            this.alert = {
              type: 'success',
              message: data.success,
            };    
            
            this.newsletter_name = '';
            this.newsletter_email = '';
          }
        })
        .catch(err => console.log(err));
    },
    async getData() {
      await axiosApi({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        url: BASE_URL + '/index.php?route=common/module_newsletter',
        method: 'GET',
      })
        .then(({ data }) => {
          this.enableNewsletterName = data.enableNewsletterName;
          this.newsletter_status = data.newsletter_status;
        })
        .catch(err => console.log(err));
    },    
    async validateEmail() {
      if (!this.newsletter_email) return;

      return await axiosApi({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        url: BASE_URL + '/index.php?route=common/module_newsletter/validateEmail',
        method: 'post',
        data: 'newsletter_email=' + this.newsletter_email,
      })
        .then(({ data }) => {
          if (data.errors) this.$refs.validationObserver.setErrors(data.errors);
        })
        .catch(err => console.log(err));
    },
  },
  created() {
    this.getData();
  }
}
</script>

<style scoped>
.title-style {
  max-width: fit-content;
}
.field-style {
  width: 45%;
}
.field-style--email {
  width: 90%;
}
.button__newsletter {
  background-color: transparent;
  border-color: transparent;
}
@media only screen and (max-width: 991px) {
  .field-style {
    width: 100%;
    padding: 4px 0 !important;
  }
  .field-style--email {
    width: 100%;
  }
}
</style>