<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'

const router = useRouter()
const route = useRoute()
const activeSave = useActiveSave()

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  documentNo: '',
  description: '',
  isApproved: false,
  processed: false,
  creditCardNumber: 0,
  creditCardExpMM: Number(new Date().getMonth()) + 1,
  creditCardExpYY: new Date().getFullYear(),
  creditCardVV: '',
  isReconciled: false,
  taxAmt: 0,
  discountAmt: 0,
  payAmt: 0,
  dateTrx: date.now('date'),
  isAllocated: false,
  isOnline: false,
  isReceipt: true,
  writeOffAmt: 0,
  overUnderAmt: 0,
  isOverUnderPayment: false,
  isSelfService: false,
  isDelayedCapture: false,
  chargeAmt: 0,
  R_CVV2Match: 0,
  dateAcct: date.now('date'),
  isPrepayment: false,
  processedOn: 0,
  isVoided: false,
  isOverrideCurrencyRate: false,
  routingNo: '',
  accountNo: '',
  A_Zip: '',
  A_Ident_DL: '',
  A_Ident_SSN: '',
  A_EMail: '',
  voiceAuthCode: '',
  orig_TrxID: '',
  micr: '',
  checkNo: '',
  A_Name: '',
  A_Street: '',
  A_City: '',
  A_State: '',
  A_Country: '',
  swiftCode: '',
  creditCardType: '',
  creditCardTypeId: '',
  bankAccount: '',
  bankAccountId: '',
  trxType: '',
  trxTypeId: '',
  tenderType: '',
  tenderTypeId: '',
  currency: '',
  currencyId: '',
  docType: 'AR Receipt',
  docTypeId: '119',
  order: '',
  orderId: '',
  invoice: '',
  invoiceId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  partner: '',
  partnerId: '',
  charge: '',
  chargeId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/payments/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: '',
      uid: '',
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      isActive: res?.IsActive ?? true,
      documentNo: '',
      description: res?.Description || '',
      isApproved: false,
      processed: false,
      creditCardNumber: res?.CreditCardNumber || 0,
      creditCardExpMM: res?.CreditCardExpMM || Number(new Date().getMonth()) + 1,
      creditCardExpYY: res?.CreditCardExpYY || new Date().getFullYear(),
      creditCardVV: res?.CreditCardVV || '',
      isReconciled: false,
      taxAmt: res?.TaxAmt || 0,
      discountAmt: res?.DiscountAmt || 0,
      payAmt: res?.PayAmt || 0,
      dateTrx: res?.DateTrx || date.now('date'),
      isAllocated: false,
      isOnline: false,
      isReceipt: true,
      writeOffAmt: res?.WriteOffAmt || 0,
      overUnderAmt: res?.OverUnderAmt || 0,
      isOverUnderPayment: res?.IsOverUnderPayment ?? false,
      isSelfService: false,
      isDelayedCapture: false,
      chargeAmt: res?.ChargeAmt || 0,
      R_CVV2Match: res?.R_CVV2Match || 0,
      dateAcct: res?.DateAcct || date.now('date'),
      isPrepayment: false,
      processedOn: 0,
      isVoided: false,
      isOverrideCurrencyRate: false,
      routingNo: res?.RoutingNo || '',
      accountNo: res?.AccountNo || '',
      A_Zip: res?.A_Zip || '',
      A_Ident_DL: res?.A_Ident_DL || '',
      A_Ident_SSN: res?.A_Ident_SSN || '',
      A_EMail: res?.A_EMail || '',
      voiceAuthCode: res?.VoiceAuthCode || '',
      orig_TrxID: res?.Orig_TrxID || '',
      micr: res?.Micr || '',
      checkNo: res?.CheckNo || '',
      A_Name: res?.A_Name || '',
      A_Street: res?.A_Street || '',
      A_City: res?.A_City || '',
      A_State: res?.A_State || '',
      A_Country: res?.A_Country || '',
      swiftCode: res?.SwiftCode || '',
      creditCardType: res?.CreditCardType?.identifier || '',
      creditCardTypeId: res?.CreditCardType?.id || '',
      bankAccount: res?.C_BankAccount_ID?.identifier || '',
      bankAccountId: res?.C_BankAccount_ID?.id || '',
      trxType: res?.TrxType?.identifier || '',
      trxTypeId: res?.TrxType?.id || '',
      tenderType: res?.TenderType?.identifier || '',
      tenderTypeId: res?.TenderType?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      docType: res?.C_DocType_ID?.identifier || 'AR Receipt',
      docTypeId: res?.C_DocType_ID?.id || '119',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      invoice: res?.C_Invoice_ID?.identifier || '',
      invoiceId: res?.C_Invoice_ID?.id || '',
      docStatus: 'Draft',
      docStatusId: 'DR',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      charge: res?.C_Charge_ID?.identifier || '',
      chargeId: res?.C_Charge_ID?.id || '',
      project: res?.C_Project_ID?.identifier || '',
      projectId: res?.C_Project_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
  
    setActiveSave()
  }
}
onMounted(retrieve)

const setActiveSave = () => {
  if(form.value.bankAccountId !== '' && form.value.docTypeId !== '' && form.value.dateTrx !== '' && form.value.dateAcct !== '' && form.value.payAmt !== '' && form.value.tenderTypeId !== '' && form.value.partnerId !== '' && form.value.currencyId !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    router.push('/procurements/payments')
  }
}

const save = async (record) => {
  form.value = record
  
  setActiveSave()
}

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/payments/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      description: form.value.description,
      isApproved: form.value.isApproved,
      processed: form.value.processed,
      creditCardNumber: form.value.creditCardNumber,
      creditCardExpMM: form.value.creditCardExpMM,
      creditCardExpYY: form.value.creditCardExpYY,
      isReconciled: form.value.isReconciled,
      taxAmt: form.value.taxAmt,
      discountAmt: form.value.discountAmt,
      payAmt: form.value.payAmt,
      dateTrx: form.value.dateTrx,
      isAllocated: form.value.isAllocated,
      isOnline: form.value.isOnline,
      isReceipt: form.value.isReceipt,
      writeOffAmt: form.value.writeOffAmt,
      overUnderAmt: form.value.overUnderAmt,
      isOverUnderPayment: form.value.isOverUnderPayment,
      isSelfService: form.value.isSelfService,
      isDelayedCapture: form.value.isDelayedCapture,
      chargeAmt: form.value.chargeAmt,
      R_CVV2Match: form.value.R_CVV2Match,
      dateAcct: form.value.dateAcct,
      isPrepayment: form.value.isPrepayment,
      processedOn: form.value.processedOn,
      isVoided: form.value.isVoided,
      isOverrideCurrencyRate: form.value.isOverrideCurrencyRate,
      routingNo: form.value.routingNo,
      accountNo: form.value.accountNo,
      A_Zip: form.value.A_Zip,
      A_Ident_DL: form.value.A_Ident_DL,
      A_Ident_SSN: form.value.A_Ident_SSN,
      A_EMail: form.value.A_EMail,
      voiceAuthCode: form.value.voiceAuthCode,
      orig_TrxID: form.value.orig_TrxID,
      micr: form.value.micr,
      checkNo: form.value.checkNo,
      A_Name: form.value.A_Name,
      A_Street: form.value.A_Street,
      A_City: form.value.A_City,
      A_State: form.value.A_State,
      A_Country: form.value.A_Country,
      swiftCode: form.value.swiftCode,
      creditCardTypeId: form.value.creditCardTypeId,
      bankAccountId: form.value.bankAccountId,
      trxTypeId: form.value.trxTypeId,
      tenderTypeId: form.value.tenderTypeId,
      currencyId: form.value.currencyId,
      docTypeId: form.value.docTypeId,
      orderId: form.value.orderId,
      invoiceId: form.value.invoiceId,
      docStatusId: form.value.docStatusId,
      partnerId: form.value.partnerId,
      chargeId: form.value.chargeId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
    }
  })

  if(Number(res.status) === 200 && Number(res.id) !== 0) {
    form.value.alert.processing = false
    activeSave.value = false

    if(saveType === 'preview') {
      router.push('/procurements/payments/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/procurements/payments/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      back()
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = false
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Procurements'},
  { link: '/procurements/payments', text: 'Payments'},
  { link: '#', text: 'Add Payment', active: true}
]))

const tab = ref(route.query?.tab || 'payment')
const tabs = computed(() => ([
  { value: 'payment', text: 'Payment'},
  { value: 'reference', text: 'Allocate & Reference'},
  { value: 'amounts', text: 'Amounts'},
  { value: 'document', text: 'Document'},
  { value: 'status', text: 'Status'}
]))

const openOtherTab = () => {
  if(tab.value === 'payment') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'amounts'
  } else if(tab.value === 'amounts') {
    tab.value = 'document'
  } else if(tab.value === 'document') {
    tab.value = 'status'
  }
}
</script>

<template>
  <Head>
    <Title>Add Payment</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    
    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" @click="submit('onlysave')" class="button" :class="(form.bankAccountId === '' || form.docTypeId === '' || form.dateTrx === '' || form.dateAcct === '' || form.payAmt === '' || form.tenderTypeId === '' || form.currencyId === '' || form.partnerId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <button v-if="tab !== 'status'" type="button" @click="openOtherTab" class="button">Next</button>
      </div>
      <div>
        <div class="d-flex gap-10px">
          <button v-if="activeSave" type="button" @click="activeSave = false; back();" class="button">
            <span class="tf-icon ti ti-square-x ti-xs me-1 color-inherit"></span> Abort
          </button>
          <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>
    
    <div class="banner">
      <div class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <ProcurementsPaymentForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
    </div>
  </NuxtLayout>
</template>