<script setup>

import dayjs from "dayjs";
import {useSupabaseSelect} from "~/composables/useSupabase.js";

let unallocatedStatements = ref(0)
let bankaccounts = ref([])

const setupPage = async () => {
  let bankstatements = (await useEntities("bankstatements").select("*, statementallocations(*)","date",true)).filter(i => !i.archived)
  unallocatedStatements.value = bankstatements.filter(i => Number(calculateOpenSum(i)) !== 0).length
  bankaccounts.value = await useEntities("bankaccounts").select()
}

setupPage()

const calculateOpenSum = (statement) => {
  let startingAmount = 0

  statement.statementallocations.forEach(item => {
    startingAmount += item.amount
  })

  return (statement.amount - startingAmount).toFixed(2)
}
</script>

<template>
  <table>

    <tr>
      <td colspan="2">Nicht zugewiesene Bankbuchungen:</td>
      <td>
        <span v-if="unallocatedStatements > 0" class="text-orange-500 font-bold">{{unallocatedStatements}}</span>
        <span v-else class="text-primary-500 font-bold">0</span>
      </td>
    </tr>
    <tr v-for="account in bankaccounts.filter(i => !i.expired)">
      <td>{{ account.name }}:</td>
      <td>
        {{dayjs(account.synced_at).format("DD.MM.YY HH:mm")}}
      </td>
      <td>
        <span v-if="account.balance < 0" class=" text-nowrap text-rose-600 font-bold">{{useCurrency(account.balance)}}</span>
        <span v-else-if="account.balance > 0" class="text-nowrap text-primary-500 font-bold">{{useCurrency(account.balance)}}</span>
        <span v-else class="text-nowrap ">{{useCurrency(account.balance)}}</span>
      </td>
    </tr>
  </table>

</template>

<style scoped>

</style>