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

class ProfileController extends GetxController {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  var name = ''.obs;
  var email = ''.obs;
  var isLoading = true.obs;

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

  Future<void> loadProfile() async {
    try {
      isLoading.value = true;
      final user = _auth.currentUser;
      if (user != null) {
        email.value = user.email ?? "";

        final doc =
            await _firestore.collection('users').doc(user.uid).get();

        if (doc.exists) {
          name.value = doc.data()?['name'] ?? "";
        }
      }
    } catch (e) {
      Get.snackbar("Error", "Gagal memuat profil: $e");
    } finally {
      isLoading.value = false;
    }
  }

Future<void> updateName() async {
  try {
    final user = _auth.currentUser;
    if (user == null) return;

    /// ✅ VALIDASI NAMA
    if (name.value.trim().isEmpty) {
      Get.snackbar(
        "Peringatan",
        "Nama tidak boleh kosong",
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.white,
        colorText: Colors.black,
        margin: const EdgeInsets.all(12),
        borderRadius: 12,
        duration: const Duration(seconds: 2),
      );
      return;
    }

    await _firestore
        .collection('users')
        .doc(user.uid)
        .update({
      "name": name.value.trim(),
    });

    Get.snackbar(
      "Berhasil",
      "Nama pengguna berhasil diperbarui",
      snackPosition: SnackPosition.TOP,
      backgroundColor: Colors.white,
      colorText: Colors.black,
      margin: const EdgeInsets.all(12),
      borderRadius: 12,
      duration: const Duration(seconds: 2),
    );

  } catch (e) {
    Get.snackbar(
      "Error",
      "Gagal memperbarui nama",
      snackPosition: SnackPosition.TOP,
      backgroundColor: Colors.white,
      colorText: Colors.black,
      margin: const EdgeInsets.all(12),
      borderRadius: 12,
      duration: const Duration(seconds: 2),
    );
  }
}

}
