<template>
  <div>
    <h1>Kontaktpersonen Verwaltung</h1>
    <ContactPersonForm
      :contactPerson="selectedContactPerson"
      :positions="positions"
      @contactPersonSaved="fetchContactPersons"
    />
    <ul>
      <li v-for="contactPerson in contactPersons" :key="contactPerson.id" @click="selectContactPerson(contactPerson)">
        {{ contactPerson.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';
import ContactPersonForm from '../../components/ContactPersonForm.vue';

export default {
  name: 'ContactPersonManagement',
  components: {
    ContactPersonForm
  },
  data() {
    return {
      contactPersons: [],
      selectedContactPerson: {
        name: '',
        phone: '',
        street: '',
        zipcode: '',
        city: '',
        email: '',
        expiryDate: null,
        positions: []
      },
      positions: []
    };
  },
  created() {
    this.fetchContactPersons();
    this.fetchPositions();
  },
  methods: {
    async fetchContactPersons() {
      try {
        const response = await axios.get('/contact-persons');
        this.contactPersons = response.data;
      } catch (error) {
        console.error('Fehler beim Abrufen der Kontaktpersonen:', error);
      }
    },
    async fetchPositions() {
      try {
        const response = await axios.get('/positions');
        this.positions = response.data;
      } catch (error) {
        console.error('Fehler beim Abrufen der Positionen:', error);
      }
    },
    selectContactPerson(contactPerson) {
      this.selectedContactPerson = contactPerson;
    }
  }
};
</script>

<style scoped>
ul {
  list-style-type: none;
  padding: 0;
}
li {
  cursor: pointer;
  padding: 5px;
  margin: 5px 0;
  background-color: #f0f0f0;
}
li:hover {
  background-color: #e0e0e0;
}
</style>
