<script setup>
const router = useRouter()

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

const form = ref({
  id: '',
  organizationId: '',
  isActive: true,
  iso_code: '',
  stdPrecision: 2,
  description: '',
  costingPrecision: 4,
  curSymbol: '',
  isEuro: false,
  isEMUMember: false,
  emuRate: 0,
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

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

const save = async (record, id = '') => {
  const res = await $fetch('/api/settings/currencies/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: record.organizationId,
      isActive: record.isActive,
      iso_code: record.iso_code,
      stdPrecision: record.stdPrecision,
      description: record.description,
      costingPrecision: record.costingPrecision,
      curSymbol: record.curSymbol,
      isEuro: record.isEuro,
      isEMUMember: record.isEMUMember,
      emuRate: record.emuRate,
    }
  })

  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/currencies', text: 'Currencies'},
  { link: '#', text: 'Add Currency', active: true}
]))
</script>

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

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