<script setup>
import { date } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'
import { toast } from 'bulma-toast'

const route = useRoute()
const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const clientName = ref('')
onMounted(() => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
})

const props = defineProps({
  action: String,
  info: Object
})

const entries = ref([])
const form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  partner: props.info?.name || '',
  partnerId: props.info?.id || '',
  isActive: true,
  isACH: false,
  accountNo: '',
  routingNo: '',
  iban: '',
  accountName: '',
  accountEmail: '',
  accountCity: '',
  accountState: '',
  accountStreet: '',
  accountZip: '',
  accountIdentDL: '',
  accountIdentSSN: '',
  accountCountry: '',
  creditCardExpMM: 27,
  creditCardExpYY: 2000,
  creditCardVV: '000',
  creditCardNumber: '',
  bank: '',
  bankId: '',
  user: '',
  userId: '',
  rAvsAddr: '',
  rAvsAddrId: '',
  bankAccountType: '',
  bankAccountTypeId: '',
  bpBankAcctUse: 'Both',
  bpBankAcctUseId: 'B',
  creditCardType: '',
  creditCardTypeId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || organizationId.value || ''
  form.value.partner = props.info?.name || ''
  form.value.partnerId = props.info?.id || ''
})

const showDetailRecordModal = ref(false)
const resetDetailRecordModal = () => {
  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    partner: props.info?.name || '',
    partnerId: props.info?.id || '',
    isActive: true,
    isACH: false,
    accountNo: '',
    routingNo: '',
    iban: '',
    accountName: '',
    accountEmail: '',
    accountCity: '',
    accountState: '',
    accountStreet: '',
    accountZip: '',
    accountIdentDL: '',
    accountIdentSSN: '',
    accountCountry: '',
    creditCardExpMM: 27,
    creditCardExpYY: 2000,
    creditCardVV: '000',
    creditCardNumber: '',
    bank: '',
    bankId: '',
    user: '',
    userId: '',
    rAvsAddr: '',
    rAvsAddrId: '',
    bankAccountType: '',
    bankAccountTypeId: '',
    bpBankAcctUse: 'Both',
    bpBankAcctUseId: 'B',
    creditCardType: '',
    creditCardTypeId: '',
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }
}
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false
  resetDetailRecordModal()
}

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/bank-accounts', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || item?.uid || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          partner: item?.C_BPartner_ID?.identifier || '',
          partnerId: item?.C_BPartner_ID?.id || '',
          isActive: item?.IsActive ?? true,
          isACH: item?.IsACH ?? false,
          accountNo: item?.AccountNo || '',
          routingNo: item?.RoutingNo || '',
          iban: item?.IBAN || '',
          accountName: item?.A_Name || '',
          accountEmail: item?.A_EMail || '',
          accountCity: item?.A_City || '',
          accountState: item?.A_State || '',
          accountStreet: item?.A_Street || '',
          accountZip: item?.A_Zip || '',
          accountIdentDL: item?.A_Ident_DL || '',
          accountIdentSSN: item?.A_Ident_SSN || '',
          accountCountry: item?.A_Country || '',
          creditCardExpMM: item?.CreditCardExpMM || 27,
          creditCardExpYY: item?.CreditCardExpYY || 2000,
          creditCardVV: item?.CreditCardVV || '000',
          creditCardNumber: item?.CreditCardNumber || '',
          bank: item?.C_Bank_ID?.identifier || '',
          bankId: item?.C_Bank_ID?.id || '',
          user: item?.AD_User_ID?.identifier || '',
          userId: item?.AD_User_ID?.id || '',
          rAvsAddr: item?.R_AvsAddr?.identifier || '',
          rAvsAddrId: item?.R_AvsAddr?.id || '',
          bankAccountType: item?.BankAccountType?.identifier || '',
          bankAccountTypeId: item?.BankAccountType?.id || '',
          bpBankAcctUse: item?.BPBankAcctUse?.identifier || 'Both',
          bpBankAcctUseId: item?.BPBankAcctUse?.id || 'B',
          creditCardType: item?.CreditCardType?.identifier || '',
          creditCardTypeId: item?.CreditCardType?.id || '',
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  //entries.value.splice(index, 1)

  if(entry.id) {
    const res = await $fetch('/api/partners/partners/'+entry.id+'/bank-accounts', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      retrieve()
    }
  }
}

const save = async () => {
  console.log(form.value)
  if(form.value.id !== '') {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/bank-accounts', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        isACH: form.value.isACH,
        accountNo: form.value.accountNo,
        routingNo: form.value.routingNo,
        iban: form.value.iban,
        accountName: form.value.accountName,
        accountEmail: form.value.accountEmail,
        accountCity: form.value.accountCity,
        accountState: form.value.accountState,
        accountStreet: form.value.accountStreet,
        accountZip: form.value.accountZip,
        accountIdentDL: form.value.accountIdentDL,
        accountIdentSSN: form.value.accountIdentSSN,
        accountCountry: form.value.accountCountry,
        creditCardExpMM: form.value.creditCardExpMM,
        creditCardExpYY: form.value.creditCardExpYY,
        creditCardVV: form.value.creditCardVV,
        creditCardNumber: form.value.creditCardNumber,
        bankId: form.value.bankId,
        userId: form.value.userId,
        rAvsAddrId: form.value.rAvsAddrId,
        bankAccountTypeId: form.value.bankAccountTypeId,
        bpBankAcctUseId: form.value.bpBankAcctUseId,
        creditCardTypeId: form.value.creditCardTypeId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/bank-accounts', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        isACH: form.value.isACH,
        accountNo: form.value.accountNo,
        routingNo: form.value.routingNo,
        iban: form.value.iban,
        accountName: form.value.accountName,
        accountEmail: form.value.accountEmail,
        accountCity: form.value.accountCity,
        accountState: form.value.accountState,
        accountStreet: form.value.accountStreet,
        accountZip: form.value.accountZip,
        accountIdentDL: form.value.accountIdentDL,
        accountIdentSSN: form.value.accountIdentSSN,
        accountCountry: form.value.accountCountry,
        creditCardExpMM: form.value.creditCardExpMM,
        creditCardExpYY: form.value.creditCardExpYY,
        creditCardVV: form.value.creditCardVV,
        creditCardNumber: form.value.creditCardNumber,
        bankId: form.value.bankId,
        userId: form.value.userId,
        rAvsAddrId: form.value.rAvsAddrId,
        bankAccountTypeId: form.value.bankAccountTypeId,
        bpBankAcctUseId: form.value.bpBankAcctUseId,
        creditCardTypeId: form.value.creditCardTypeId,
        partnerId: form.value.partnerId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>User</th>
            <th>Account Name</th>
            <th class="w-100px">Active</th>
            <th class="w-100px">ACH</th>
            <th v-if="action !== 'view'" class="w-100px">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 5 : 4" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.user }}</td>
            <td>{{ entry.accountName }}</td>
            <td class="textAlignCenter">
              <div class="check">
                <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" disabled>
                <!--<label class="checkLabel" :for="'isActive_'+index">Active</label>-->
              </div>
            </td>
            <td class="textAlignCenter">
              <div class="check">
                <input type="checkbox" v-model="entry.isACH" class="checkInput" :id="'isACH_'+index" :checked="entry.isACH" disabled>
                <!--<label class="checkLabel" :for="'isACH_'+index">ACH</label>-->
              </div>
            </td>
            <td v-if="action !== 'view'">
              <div class="d-flex justify-flexEnd gap-5px">
                <span @click="form = entry; showDetailRecordModal = true;" class="cursor-pointer fg-warning">
                  <i class="menu-icon tf-icons ti ti-pencil"></i>
                </span>
                <span @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                  <i class="menu-icon tf-icons ti ti-trash"></i>
                </span>
              </div>
            </td>
          </tr>
          <tr v-if="action !== 'view'">
            <td colspan="5">
              <button type="button" @click="resetDetailRecordModal(); showDetailRecordModal = true;" class="button">Add Record</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <div class="modal" :class="{'active': showDetailRecordModal}" :style="{display: showDetailRecordModal ? 'block' : 'none'}">
      <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeDetailRecordModal">
        <div class="modalContent">
          <div class="modalHeader">
            <h3 class="modalTitle">Bank Account</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
          <div class="modalBody">
            <div class="my-5 mx-5">
              <AlertAction v-model='form.alert.status' :alert="form.alert" />
              <div class="columns">
                <div class="column is-two-thirds">
                  <div class="columns">
                    <div class="column" :class="!form.isACH ? 'is-half' : 'is-full'">
                      <label class="label d-block">User</label>
                      <ClientOnly>
                        <SelectBox v-model="form.userId" :options="getOptions?.['users']?.records || [{id: form.userId, Name: form.user}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions(`partners/partners/${form.partnerId}/users`, 'users')" :loading="loading?.['users'] ?? true" />
                      </ClientOnly>
                    </div>
                    <div v-if="!form.isACH" class="column is-half">
                      <label class="label d-block">Credit Card</label>
                      <select v-model="form.creditCardTypeId" class="select">
                        <option value="A">Amex</option>
                        <option value="D">Diners</option>
                        <option value="N">Discover</option>
                        <option value="M">MasterCard</option>
                        <option value="P">Purchase Card</option>
                        <option value="V">Visa</option>
                      </select>
                    </div>
                  </div>

                  <div v-if="form.isACH" class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Bank *</label>
                      <ClientOnly>
                        <SelectBox v-model="form.bankId" :options="getOptions?.['banks']?.records || [{id: form.bankId, Name: form.bank}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_bank', 'banks')" @change="(val, opt) => form.routingNo = opt.RoutingNo" :loading="loading?.['banks'] ?? true" />
                      </ClientOnly>

                      <label class="label d-block mt-2">Account No</label>
                      <input type="text" v-model="form.accountNo" class="input" />

                      <label class="label d-block mt-2">IBAN</label>
                      <input type="text" v-model="form.iban" class="input" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Bank Account Type</label>
                      <select v-model="form.bankAccountTypeId" class="select">
                        <option value="D">Card</option>
                        <option value="B">Cash</option>
                        <option value="C">Checking</option>
                        <option value="S">Savings</option>
                      </select>
                      
                      <label class="label d-block mt-2">Account Usage</label>
                      <select v-model="form.bpBankAcctUseId" class="select">
                        <option value="B">Both</option>
                        <option value="D">Direct Debit</option>
                        <option value="T">Direct Deposit</option>
                        <option value="N">None</option>
                      </select>

                      <template v-if="form.routingNo === ''">
                        <label class="label d-block mt-2">Routing No</label>
                        <input type="text" v-model="form.routingNo" class="input" />
                      </template>
                    </div>
                  </div>

                  <div v-else class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Number</label>
                      <input type="text" v-model="form.creditCardNumber" class="input" />

                      <label class="label d-block mt-2">Exp. Month</label>
                      <input type="text" v-model="form.creditCardExpMM" class="input" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Verification Code</label>
                      <input type="text" v-model="form.creditCardVV" class="input" />

                      <label class="label d-block mt-2">Exp. Year</label>
                      <input type="text" v-model="form.creditCardExpYY" class="input" />
                    </div>
                  </div>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Account Name *</label>
                      <input type="text" v-model="form.accountName" class="input" />

                      <label class="label d-block mt-2">Account Email</label>
                      <input type="email" v-model="form.accountEmail" class="input" />

                      <label class="label d-block mt-2">Driver License</label>
                      <input type="text" v-model="form.accountIdentDL" class="input" />

                      <label class="label d-block mt-2">Social Security No</label>
                      <input type="text" v-model="form.accountIdentSSN" class="input" />
                      
                      <label class="label d-block mt-2">Customer Payment Profile ID</label>
                      <input type="text" class="input" readonly />
                      
                      <label class="label d-block mt-2">Payment Processor</label>
                      <input type="text" class="input" readonly />

                      <label class="label d-block mt-2">Address Verified</label>
                      <input type="text" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Account Street</label>
                      <input type="text" v-model="form.accountStreet" class="input" />

                      <label class="label d-block mt-2">Account City</label>
                      <input type="text" v-model="form.accountCity" class="input" />

                      <label class="label d-block mt-2">Account State/Province</label>
                      <input type="text" v-model="form.accountState" class="input" />

                      <label class="label d-block mt-2">Account Country</label>
                      <input type="text" v-model="form.accountCountry" class="input" />

                      <label class="label d-block mt-2">Account Zip/Postal</label>
                      <input type="text" v-model="form.accountZip" class="input" />
                      
                      <label class="label d-block mt-2">Zip Verified</label>
                      <input type="text" class="input" readonly />
                    </div>
                  </div>
                </div>
                <div class="column is-one-third">
                  <label class="label d-block">Organization *</label>
                  <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {form.organization = opt.Name; save();}" :loading="loading?.['orgs'] ?? true" />

                  <label class="label d-block mt-2">Tenant *</label>
                  <input type="text" :value="form.client" class="input" readonly />

                  <label class="label d-block mt-2">Business Partner *</label>
                  <input type="text" :value="form.partner" class="input" readonly />

                  <label class="label d-block mt-2">Status</label>
                  <div class="d-flex flexDirection-column">
                    <div class="check">
                      <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive">
                      <label class="checkLabel" for="isActive">Active</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isACH" class="checkInput" id="isACH" :checked="form.isACH">
                      <label class="checkLabel" for="isACH">ACH</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modalFooter">
            <div></div>
            <div class="d-flex gap-10px">
              <button type="button" class="button" @click="closeDetailRecordModal">Close</button>
              <button type="button" class="button" @click="save" :class="(form.userId === '' || form.accountName === '' || (form.isACH === true && form.bankId === '') || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>