import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class KebunController extends GetxController {
  final namaKebunC = TextEditingController();
  final alamatC = TextEditingController();
  final tanamanC = TextEditingController();
  final namaPetaniC = TextEditingController();

  // Method untuk simpan + validasi
  Future<void> simpanKebun() async {
    if (namaKebunC.text.isEmpty ||
        alamatC.text.isEmpty ||
        tanamanC.text.isEmpty ||
        namaPetaniC.text.isEmpty) {
      Get.snackbar('Error', 'Semua field harus diisi!');
      return;
    }

    try {
      await FirebaseFirestore.instance.collection('kebun').add({
        'nama_kebun': namaKebunC.text,
        'alamat': alamatC.text,
        'tanaman': tanamanC.text,
        'nama_petani': namaPetaniC.text,
      });

      Get.snackbar('Berhasil', 'Data kebun berhasil disimpan');

      // Kosongkan input
      namaKebunC.clear();
      alamatC.clear();
      tanamanC.clear();
      namaPetaniC.clear();
    } catch (e) {
      Get.snackbar('Error', 'Gagal menyimpan data: $e');
    }
  }

  @override
  void onClose() {
    namaKebunC.dispose();
    alamatC.dispose();
    tanamanC.dispose();
    namaPetaniC.dispose();
    super.onClose();
  }
}
