<script setup>
import { date } from 'alga-js'
const router = useRouter()
const route = useRoute()

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  name: '',
  description: '',
  isActive: true,
  isDefault: false,
  isDocumentLevel: false,
  isSummary: false,
  isTaxExempt: false,
  isSalesTax: false,
  validFrom: date.now('date'),
  rate: 6,
  requiresTaxCertificate: false,
  taxIndicator: '6%CT',
  countryGroup: '',
  countryGroupId: '',
  country: '',
  countryId: '',
  region: '',
  regionId: '',
  toCountryGroup: '',
  toCountryGroupId: '',
  toCountry: '',
  toCountryId: '',
  toRegion: '',
  toRegionId: '',
  taxCategory: '',
  taxCategoryId: '',
  SOPOType: '',
  SOPOTypeId: '',
  taxPostingIndicator: '',
  taxPostingIndicatorId: '',
  taxProvider: '',
  taxProviderId: '',
  parentTax: '',
  parentTaxId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/settings/tax-rates/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      name: res?.Name || '',
      description: res?.Description || '',
      isActive: res?.IsActive ?? true,
      isDefault: res?.IsDefault ?? false,
      isDocumentLevel: res?.IsDocumentLevel ?? false,
      isSummary: res?.IsSummary ?? false,
      isTaxExempt: res?.IsTaxExempt ?? false,
      isSalesTax: res?.IsSalesTax ?? false,
      validFrom: res?.ValidFrom || date.now('date'),
      rate: res?.Rate || 6,
      requiresTaxCertificate: res?.RequiresTaxCertificate ?? false,
      taxIndicator: res?.TaxIndicator || '6%CT',
      countryGroup: res?.C_CountryGroup_ID?.identifier || '',
      countryGroupId: res?.C_CountryGroup_ID?.id || '',
      country: res?.C_Country_ID?.identifier || '',
      countryId: res?.C_Country_ID?.id || '',
      region: res?.C_Region_ID?.identifier || '',
      regionId: res?.C_Region_ID?.id || '',
      toCountryGroup: res?.To_CountryGroup_ID?.identifier || '',
      toCountryGroupId: res?.To_CountryGroup_ID?.id || '',
      toCountry: res?.To_Country_ID?.identifier || '',
      toCountryId: res?.To_Country_ID?.id || '',
      toRegion: res?.To_Region_ID?.identifier || '',
      toRegionId: res?.To_Region_ID?.id || '',
      taxCategory: res?.C_TaxCategory_ID?.identifier || '',
      taxCategoryId: res?.C_TaxCategory_ID?.id || '',
      SOPOType: res?.SOPOType?.identifier || '',
      SOPOTypeId: res?.SOPOType?.id || '',
      taxPostingIndicator: res?.TaxPostingIndicator?.identifier || '',
      taxPostingIndicatorId: res?.TaxPostingIndicator?.id || '',
      taxProvider: res?.C_TaxProvider_ID?.identifier || '',
      taxProviderId: res?.C_TaxProvider_ID?.id || '',
      parentTax: res?.Parent_Tax_ID?.identifier || '',
      parentTaxId: res?.Parent_Tax_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
  }
}
onMounted(retrieve)

const back = () => {
  router.push('/settings/tax-rates')
}

const save = async (record, id = '', saveType = '') => {
  const res = await $fetch('/api/settings/tax-rates/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: record.id,
      organizationId: record.organizationId,
      name: record.name,
      description: record.description,
      isActive: record.isActive,
      isDefault: record.isDefault,
      isDocumentLevel: record.isDocumentLevel,
      isSummary: record.isSummary,
      isTaxExempt: record.isTaxExempt,
      isSalesTax: record.isSalesTax,
      validFrom: record.validFrom,
      rate: record.rate,
      requiresTaxCertificate: record.requiresTaxCertificate,
      taxIndicator: record.taxIndicator,
      countryGroupId: record.countryGroupId,
      countryId: record.countryId,
      regionId: record.regionId,
      toCountryGroupId: record.toCountryGroupId,
      toCountryId: record.toCountryId,
      toRegionId: record.toRegionId,
      taxCategoryId: record.taxCategoryId,
      SOPOTypeId: record.SOPOTypeId,
      taxPostingIndicatorId: record.taxPostingIndicatorId,
      taxProviderId: record.taxProviderId,
      parentTax: record.parentTax,
      parentTaxId: record.parentTaxId
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/settings/tax-rates/'+res.id+'/view')
    } else if(saveType === 'changes') {
      form.value.processing = false
      location.reload()
    } else {
      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/tax-rates', text: 'Tax Rates'},
  { link: '#', text: 'Add Tax Rate', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Tax Rate</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"></span> Back
            </button>
          </div>
        </div>
        <div>
          <SettingsTaxRateForm v-model="form" @save="save"/>
        </div>
      </div>

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