<script>
  import { _ } from "svelte-i18n";
  import store from "../../store";
  import AddDonorModal from "./AddDonorModal.svelte";
  import DonorsOverview from "./DonorsOverview.svelte";
  $: current_donors = [];
  export let modal_open = false;
  let addDonors;
</script>

<section class="container p-5">
  <h4 class="mb-1 text-3xl font-extrabold leading-tight">
    {$_("donors")}
  </h4>
  {#if store.state.jwtinfo.userdetails.permissions.includes("DONOR:CREATE")}
    <button
      on:click={() => {
        modal_open = true;
      }}
      type="button"
      class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm  mb-1 lg:mb-0"
    >
      {$_("add-donor")}
    </button>
  {/if}
  {#if store.state.jwtinfo.userdetails.permissions.includes("DONOR:GET")}
    <button
      on:click={() => {
        const data = current_donors
          .filter((d) => d.receiptNeeded === true)
          .map(function (d) {
            d.address.address2 =
              d.address.address2 === "" ? "" : " " + d.address.address2;
            const address = `${d.address.address1}${d.address.address2}, ${d.address.postalcode} ${d.address.city}, ${d.address.country}`;
            return [
              d.firstname,
              d.middlename,
              d.lastname,
              (d.paidDonationAmount/100).toFixed(2),
              address,
            ];
          });
        let csv = `${$_("csv_import__firstname")};${$_(
          "csv_import__middlename"
        )};${$_("csv_import__lastname")};${$_(
          "total_donation_amount_in_eur"
        )};${$_("address")}\n`;
        data.forEach(function (row) {
          csv += row.join(";");
          csv += "\n";
        });
        let hiddenElement = document.createElement("a");
        hiddenElement.href = "data:text/csv;charset=utf-8," + encodeURI(csv);
        hiddenElement.target = "_blank";
        hiddenElement.download = `${$_(
          "filename_sponsoringquittungsliste"
        )}.csv`;
        hiddenElement.click();
        hiddenElement.remove();
      }}
      type="button"
      class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm  mb-1 lg:mb-0"
    >
      {$_("sponsoring-quittungs-liste_herunterladen")}
    </button>
  {/if}
  <DonorsOverview bind:current_donors bind:addDonors />
</section>

{#if store.state.jwtinfo.userdetails.permissions.includes("DONOR:CREATE")}
  <AddDonorModal
    on:created={(event) => {
      addDonors(event.detail.donors);
    }}
    bind:modal_open
  />
{/if}
