<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>{{ language.heading_title }}</strong>
              </span>
            </div>

            <p class="text-small visible-block vertical-margin-x-small">{{ language.text_mensagem }}</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"
                  v-model="newsletter_name"
                  :valid="valid && passed"
                  :error="errors[0]"
                  :placeholder="language.text_placeholder_name"
                >
                </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"
                  v-model="newsletter_email"
                  :valid="valid && passed"
                  :error="errors[0]"
                  :placeholder="language.text_placeholder_email"
                  @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"
                  v-model="newsletter_email"
                  :valid="valid && passed"
                  :error="errors[0]"
                  :placeholder="language.text_placeholder_email"
                  @focusout="validateEmail"
                >
                </base-input>
              </validation-provider>
            </div> 

            <button 
              type="submit" 
              class="button__newsletter text-small pointer"  
              :title="language.button_add"
            >
              <a class="text-decoration-none">
                <span>{{ language.text_to_add }}</span>
                <strong>{{ language.button_add }}</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 {
      language: {
        heading_title: 'Newsletter',
        text_mensagem: 'Cadastre-se abaixo e receba nossas novidades com exclusividade por e-mail:',
        text_placeholder_email: 'Digite seu e-mail', 
        text_placeholder_name:  'Digite seu nome',
        text_to_add: 'Clique aqui para ',
        button_add: 'Inscrever-se',
      }, 
      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,
            };     
          }
        })
        .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);
          this.alert = {
            type: 'warning',
            message: 'Error on newsletter',
          };
        })
    },    
    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>