<template>
  <div id="main">
    <div id="left">

      <UButton @click="showCreateCustomer = true">+ Kunde</UButton>
      <UModal v-model="showCreateCustomer">
        <UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
          <template #header>
            Kunde erstellen
          </template>

          <UForm @submit="createCustomer">
            <UFormGroup label="Name:" required>
              <UInput v-model="customerInfo.name"/>
            </UFormGroup>
            <UFormGroup label="Kundenummer:" required>
              <UInput type="number" v-model="customerInfo.customerNumber"/>
            </UFormGroup>
            <UButton type="submit">
              Erstellen
            </UButton>
          </UForm>


        </UCard>
      </UModal>


      <a v-for="item in customers" @click="selectItem(item)">
        <UCard class="listItem">
          <UBadge>{{item.attributes.customerNumber}}</UBadge> {{item.attributes.name}}
        </UCard>
      </a>



    </div>
    <div id="right">

      <UCard v-if="selectedItem.id">
        <template #header>
          <UBadge>{{selectedItem.attributes.customerNumber}}</UBadge> {{selectedItem.attributes.name}}
        </template>

        Kontakte:<br>
        <ul>
          <li v-for="contact in selectedItem.attributes.contacts.data">{{contact.attributes.lastName}}, {{contact.attributes.firstName}}</li>
        </ul>
<!--        {{selectedItem.attributes.contacts.data}}-->
        <br>
        Projekte:<br>
        <ul>
          <li v-for="project in selectedItem.attributes.projects.data"><router-link :to="'/projects?id=' + project.id">{{project.attributes.name}}</router-link></li>
        </ul>

        <br><br>




      </UCard>
    </div>
  </div>
</template>

<script setup>
definePageMeta({
  middleware: "auth"
})

const {find,create} = useStrapi4()
const customers = (await find('customers',{populate: "*"})).data


let showCreateCustomer = ref(false)
let customerInfo = ref({
  name: "",
  customerNumber: 0
})


let selectedItem = ref({})

const selectItem = (item) => {
  selectedItem.value = item
}

const createCustomer = async () => {
  await create('customers', customerInfo.value)
  console.log("Create")
  customerInfo.value = {}
  showCreateCustomer.value = false
}

</script>

<style scoped>
#main {
  display: flex;
  flex-direction: row;
}
#left {
  width: 25vw;
}

#right {
  width: 60vw;
  padding-left: 3vw;
}


</style>