<template>
  <div class="position-management">
    <h2>Verwalten der Rollen</h2>
    <form @submit.prevent="addPosition">
      <label for="caption">Rollenbezeichnung:</label>
      <input type="text" id="caption" v-model="newPosition.caption" placeholder="Rollenbezeichnung" required>
      <button type="submit">Speichern</button>
      <button type="button" v-if="editMode" @click="resetForm">Neue Rolle erstellen</button>
    </form>

    <table>
      <thead>
        <tr>
          <th>Rollenbezeichnung</th>
          <th>Bearbeiten</th>
          <th>Löschen</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="position in positions" :key="position.id">
          <td>{{ position.caption }}</td>
          <td><button @click="editPosition(position)">Bearbeiten</button></td>
          <td><button @click="deletePosition(position.id)">Löschen</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      positions: [],
      newPosition: {
        caption: ''
      },
      editMode: false,
      editId: null
    };
  },
  methods: {
    async fetchPositions() {
      const response = await axios.get('/positions');
      this.positions = response.data;
    },
    async addPosition() {
      if (this.editMode) {
        await axios.put(`/positions/${this.editId}`, this.newPosition);
      } else {
        const response = await axios.post('/positions', this.newPosition);
        this.positions.push(response.data);
      }
      this.resetForm();
      await this.fetchPositions();
    },
    async updatePosition(position) {
      await axios.put(`/positions/${position.id}`, position);
      this.fetchPositions(); // Refresh the list
    },
    async deletePosition(id) {
      await axios.delete(`/positions/${id}`);
      this.fetchPositions(); // Refresh the list
    },
    editPosition(position) {
      this.newPosition = { ...position };
      this.editMode = true;
      this.editId = position.id;
    },
    resetForm() {
      this.newPosition = {
        caption: ''
      };
      this.editMode = false;
      this.editId = null;
    }
  },
  created() {
    this.fetchPositions();
  }
};
</script>

<style scoped>
.position-management {
  max-width: 600px;
  margin: auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

form {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

label {
  margin-top: 10px;
}

input {
  margin-top: 5px;
  margin-bottom: 10px;
  padding: 8px;
}

button {
  margin-top: 10px;
  padding: 10px;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: left;
}

th {
  background-color: #f4f4f4;
}
</style>
