<script setup>
const router = useRouter()

definePageMeta({
  middleware: ['auth', 'org']
})

const form = ref({
  id: '',
  organizationId: '',
  name: '',
  description: '',
  isActive: true,
  countryCode: '',
  hasRegion: true,
  displaySequence: '@C@,  @P@',
  hasPostal_Add: false,
  isAddressLinesLocalReverse: false,
  isAddressLinesReverse: false,
  isPostcodeLookup: false,
  allowCitiesOutOfList: false,
  captureSequence: '@A1@ @A2@ @A3@ @A4@ @C@,  @P@ @CO@',
  currencyId: '',
  addressPrintFormat: '',
  localAddressFormat: '',
  postalCodeFormat: '',
  phoneFormat: '',
  mediaSize: '',
  bankRoutingNoFormat: '',
  bankAccountNoFormat: '',
  language: 'en_US',
  taxIDDigitGenerationClass: '',
  placeholderForAddress1: '',
  placeholderForAddress2: '',
  placeholderForAddress3: '',
  placeholderForAddress4: '',
  placeholderForAddress5: '',
  placeholderForPostal: '',
  placeholderForAdditionalZip: '',
  placeholderForCity: '',
  placeholderForComments: '',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const back = () => {
  router.push('/settings/countries')
}

const save = async (record, id = '') => {
  const res = await $fetch('/api/settings/countries/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: record.organizationId,
      name: record.name,
      description: record.description,
      isActive: record.isActive,
      countryCode: record.countryCode,
      hasRegion: record.hasRegion,
      displaySequence: record.displaySequence,
      hasPostal_Add: record.hasPostal_Add,
      isAddressLinesLocalReverse: record.isAddressLinesLocalReverse,
      isAddressLinesReverse: record.isAddressLinesReverse,
      isPostcodeLookup: record.isPostcodeLookup,
      allowCitiesOutOfList: record.allowCitiesOutOfList,
      captureSequence: record.captureSequence,
      currencyId: record.currencyId,
    }
  })

  if(Number(res.status) === 200) {
    back()
  } else {
    form.value.alert.status = res.status
    form.value.alert.message = res.message
    form.value.processing = false
    window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Settings'},
  { link: '/settings/countries', text: 'Countries'},
  { link: '#', text: 'Add Country', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Country</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <div class="banner">
        <div class="d-flex justify-between mb-3">
          <h4></h4>
          <div class="d-flex gap-0.75rem">
            <button type="button" @click="back" class="button">
              <span class="tf-icon ti ti-chevron-left ti-xs me-1 color-inherit"></span> Back
            </button>
          </div>
        </div>
        <div>
          <SettingsCountryForm v-model="form" @save="save"/>
        </div>
      </div>

    </div>
  </NuxtLayout>
</template>