import 'package:get/get.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

class StoreController extends GetxController {
  final namaTokoC = ''.obs;
  final noHpC = ''.obs;
  final alamatC = ''.obs;
  final noRegistrasiC = ''.obs;
  final keteranganC = ''.obs;

  var storeData = Rxn<Map<String, dynamic>>();
  var isLoading = false.obs;

  final uid = FirebaseAuth.instance.currentUser!.uid;

  @override
  void onInit() {
    super.onInit();
    getStoreData();
  }

  Future<void> getStoreData() async {
    isLoading.value = true;
    final doc = await FirebaseFirestore.instance.collection('stores').doc(uid).get();
    if (doc.exists) {
      storeData.value = doc.data();
      // isi obs supaya textfield terisi
      namaTokoC.value = storeData.value?['namaToko'] ?? '';
      noHpC.value = storeData.value?['noHp'] ?? '';
      alamatC.value = storeData.value?['alamat'] ?? '';
      noRegistrasiC.value = storeData.value?['noRegistrasi'] ?? '';
      keteranganC.value = storeData.value?['keterangan'] ?? '';
    }
    isLoading.value = false;
  }

  Future<void> saveStore() async {
    isLoading.value = true;
    final data = {
      'namaToko': namaTokoC.value,
      'noHp': noHpC.value,
      'alamat': alamatC.value,
      'noRegistrasi': noRegistrasiC.value,
      'keterangan': keteranganC.value,
      'updatedAt': DateTime.now(),
    };
    await FirebaseFirestore.instance.collection('stores').doc(uid).set(data);
    storeData.value = data;
    isLoading.value = false;
  }
}