<script setup>
const router = useRouter()

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

const form = ref({
  id: '',
  organizationId: '',
  address1: '',
  city: '',
  isActive: true,
  isValid: false,
  countryId: '',
  regionId: '',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

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

const save = async (record, id = '') => {
  const res = await $fetch('/api/settings/locations/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: record.organizationId,
      address1: record.address1,
      city: record.city,
      isActive: record.isActive,
      isValid: record.isValid,
      countryId: record.countryId,
      regionId: record.regionId,
    }
  })

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

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

<template>
  <Head>
    <Title>Add Location</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>
          <SettingsLocationForm v-model="form" @save="save"/>
        </div>
      </div>

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