<template>
    <div class="p-6 max-w-2xl mx-auto">
      <h2 class="text-2xl font-bold mb-6">⚙️ Student Settings</h2>
  
      <form @submit.prevent="saveSettings" class="space-y-6 bg-white p-6 rounded shadow-md">
        <div>
          <label class="block text-sm font-medium mb-1">Default Class for New Students</label>
          <select v-model="settings.defaultClass" class="w-full border px-4 py-2 rounded">
            <option v-for="cls in classes" :key="cls.id" :value="cls.id">
              {{ cls.name }} - {{ cls.section }}
            </option>
          </select>
        </div>
  
        <div>
          <label class="block text-sm font-medium mb-1">Mark Absent After</label>
          <input
            type="number"
            v-model="settings.absentAfter"
            min="1"
            class="w-full border px-4 py-2 rounded"
            placeholder="e.g. 3 days"
          />
          <p class="text-xs text-gray-500 mt-1">Auto-mark absent if not present for X consecutive days.</p>
        </div>
  
        <div class="pt-4">
          <button type="submit" class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700">
            💾 Save Settings
          </button>
        </div>
      </form>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { useDirectus } from '../../app/composables/useDirectus'
  
  const directus = useDirectus()
  const settings = ref({
    defaultClass: '',
    absentAfter: 3,
  })
  const classes = ref([])
  
  const fetchClasses = async () => {
    try {
      const { data } = await directus.items('classes').readByQuery({
        fields: ['id', 'name', 'section'],
        sort: ['name']
      })
      classes.value = data
    } catch (err) {
      console.error('Error loading classes:', err)
    }
  }
  
  const fetchSettings = async () => {
    // Load settings from a custom 'student_settings' collection or localStorage fallback
    const saved = JSON.parse(localStorage.getItem('student_settings') || '{}')
    settings.value = { ...settings.value, ...saved }
  }
  
  const saveSettings = () => {
    localStorage.setItem('student_settings', JSON.stringify(settings.value))
    alert('✅ Settings saved successfully!')
  }
  
  onMounted(() => {
    fetchSettings()
    fetchClasses()
  })
  </script>
  