<template>
  <div class="p-6 max-w-2xl mx-auto">
    <h2 class="text-2xl font-bold mb-6">Add New Student</h2>

    <form @submit.prevent="submitForm" class="space-y-4">
      <div>
        <label class="block font-medium">Name</label>
        <input v-model="form.name" type="text" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Email</label>
        <input v-model="form.email" type="email" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Phone</label>
        <input v-model="form.phone" type="text" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Date of Birth</label>
        <input v-model="form.dob" type="date" required class="input" />
      </div>

      <div>
        <label class="block font-medium">Gender</label>
        <select v-model="form.gender" required class="input">
          <option value="">Select Gender</option>
          <option value="male">Male</option>
          <option value="female">Female</option>
        </select>
      </div>

      <div>
        <label class="block font-medium">Class</label>
        <select v-model="form.class_id" required class="input">
          <option value="">Select Class</option>
          <option v-for="cls in classes" :key="cls.id" :value="cls.id">
            {{ cls.name }} - {{ cls.section }}
          </option>
        </select>
      </div>

      <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
        Submit
      </button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useDirectus } from '../../app/composables/useDirectus'

const directus = useDirectus()
const router = useRouter()

const form = ref({
  name: '',
  email: '',
  phone: '',
  dob: '',
  gender: '',
  class_id: ''
})

const classes = ref([])

onMounted(async () => {
  try {
    const data = await directus.fetchCollection('classes')
    classes.value = data
  } catch (err) {
    console.error('Error loading classes:', err)
  }
})

const submitForm = async () => {
  try {
    await directus.createItem('students', form.value)
    alert('Student added successfully!')
    router.push('/students')
  } catch (err) {
    console.error('Error adding student:', err)
    alert('Failed to add student.')
  }
}
</script>


<style scoped>
.input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 0.375rem;
}
</style>