<script setup>

let unpaidCreatedDocumentsSum = ref(0)
let unallocatedStatements = ref(0)
const setupPage = async () => {
  let documents = (await useSupabaseSelect("createddocuments","*, statementallocations(*), customer(id,name)")).filter(i => i.type === "invoices" ||i.type === "advanceInvoices")

  documents = documents.filter(i => i.statementallocations.reduce((n,{amount}) => n + amount, 0).toFixed(2) !== getDocumentSum(i).toFixed(2))

  documents.forEach(i => {
    unpaidCreatedDocumentsSum.value += getDocumentSum(i) - i.statementallocations.reduce((n,{amount}) => n + amount, 0)
  })

  let bankstatements = await useSupabaseSelect("bankstatements","*, statementallocations(*)","date",true)
  unallocatedStatements.value = bankstatements.filter(i => calculateOpenSum(i) !== 0).length
}

setupPage()

const getDocumentSum = (doc) => {
  let sum = 0
  doc.rows.forEach(row => {
    if(row.mode === "normal" || row.mode === "service" || row.mode === "free") {
      sum += row.quantity * row.price * (1 - row.discountPercent / 100) * (1 + row.taxPercent / 100)
    }
  })
  return sum
}

const calculateOpenSum = (statement) => {
  let startingAmount = statement.amount || 0

  statement.statementallocations.forEach(item => {
    if(item.cd_id) {
      startingAmount = startingAmount - item.amount
    } else if(item.ii_id) {
      startingAmount = Number(startingAmount) + item.amount
    }
  })

  return startingAmount.toFixed(2)
}

const displayCurrency = (value, currency = "€") => {
  return `${Number(value).toFixed(2).replace(".",",")} ${currency}`
}


</script>

<template>
  <table>
    <tr>
      <td>Offene Ausgangsbelege:</td>
      <td
          v-if="unpaidCreatedDocumentsSum > 0"
          class="text-rose-600 font-bold text-nowrap"
      >{{displayCurrency(unpaidCreatedDocumentsSum)}}</td>
      <td v-else class="text-primary-500 font-bold text-no-wrap">0,00€</td>
    </tr>
    <tr>
      <td>Nicht zugewiesene Bankbuchungen:</td>
      <td>
        <span v-if="unallocatedStatements > 0" class="text-rose-600 font-bold">{{unallocatedStatements}}</span>
        <span v-else class="text-primary-500 font-bold">0</span>
      </td>
    </tr>
  </table>

</template>

<style scoped>

</style>