<script setup>

import {onMounted, reactive, ref} from "vue";
import Modal from "../../../../Views/Components/Modal.vue";
import { useAjax } from "../../../../../resources/js/components/ajaxHandler.js";
import AmountInput from "../../../../Views/Components/AmountInput.vue";
import {toast} from "vue3-toastify";

const selectedTreasurers = ref([])


const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }, showTreasurers: Boolean
})

const commonProps = reactive({
    activeUsers: [],
});



onMounted(async () => {
    const response = await fetch('/api/v1/core/retrieve-global-data');
    const data = await response.json();
    Object.assign(commonProps, data);

    selectedTreasurers.value = props.data.treasurers?.map(t => t.id) ?? []
});



const mail_on_new = ref(Boolean(Number(props.data.mail_on_new)))

const emit = defineEmits(['closeTreasurers'])

const { request } = useAjax()
function closeTreasurers() {
  emit('closeTreasurers')
}


const formData = reactive({
    billingDeadline: props.data.billingDeadline,
    mailOnNew: mail_on_new.value,
    distanceAllowance: props.data.distanceAllowanceSmall,
});

async function updateCostUnit() {
    const data = await request('/api/v1/cost-unit/' + props.data.id + '/treasurers', {
        method: "POST",
        body: {
            selectedTreasurers: selectedTreasurers.value,
        }
    });

    closeTreasurers();
    if (data.status === 'success') {
        toast.success(data.message);
    } else {
        toast.error(data.message);
    }
}
</script>

<template>

  <Modal
      :show="showTreasurers"
      title="Schatzis zuweisen"
      @close="emit('closeTreasurers')"
  >
      <h3>Zuständige Schatzis:</h3>
      <p v-for="user in commonProps.activeUsers">
          <input
              type="checkbox"
              :id="'user_' + user.id"
              :value="user.id"
              v-model="selectedTreasurers"
          />
          <label :for="'user_' + user.id">{{user.fullname}}</label>
        </p>

    <input type="button" value="Speichern" @click="updateCostUnit" />
  </Modal>

</template>

<style>
.mareike-save-button {
  background-color: #2271b1 !important;
  color: #ffffff !important;
}
</style>
