import { createApp, ref, onMounted } from 'vue';

const app = createApp({
  setup() {
    const loading = ref(true);
    const saving = ref(false);
    const formData = ref([]);

    const groupedData = computed(() => {
      const groups = {};
      formData.value.forEach(item => {
        if (!groups[item.kategori]) groups[item.kategori] = { kategori: item.kategori, items: [] };
        groups[item.kategori].items.push(item);
      });
      return Object.values(groups);
    });

    async function loadData() {
      try {
        const res = await fetch('api.php?action=read&tahun=2025');
        const data = await res.json();
        formData.value = data;
      } catch (err) {
        console.error('Gagal memuat data:', err);
      } finally {
        loading.value = false;
      }
    }

    async function simpan() {
      saving.value = true;
      try {
        await fetch('api.php?action=update', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(formData.value)
        });
        alert('Data berhasil disimpan!');
      } catch (err) {
        alert('Gagal menyimpan data.');
        console.error(err);
      } finally {
        saving.value = false;
      }
    }

    onMounted(() => {
      loadData();
    });

    return {
      loading,
      saving,
      groupedData,
      simpan
    };
  }
});

app.mount('#app');