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

import '../main.dart';
import '../routs/rout_name.dart';

class LoginController extends GetxController {
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    fetchUserDetails();
  }

  TextEditingController userNameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  final formKey = GlobalKey<FormState>();

  RxBool isPass = true.obs;

  void changePass() {
    isPass.value = !isPass.value;
  }

  RxMap<String, dynamic> userDetails = RxMap();

  void fetchUserDetails() async {
    final ref = FirebaseDatabase.instance.ref("user");

    final snapshot = await ref.get();
    if (snapshot.exists) {
      final data = Map<String, dynamic>.from(snapshot.value as Map);
      userDetails.value = data;
    } else {
      userDetails.clear();
    }
  }

  void loginUser() {
    if (userNameController.text != userDetails['userName'].toString()) {
      Get.snackbar(
        'Invalid UserName',
        'Entered UserName is Invalid Please try again!',
      );
    } else if (passwordController.text != userDetails['pass'].toString()) {
      Get.snackbar(
        'Invalid Password',
        'Entered Password is Invalid Please try again!',
      );
    } else if (userDetails['isActive'] == false) {
      Get.snackbar(
        'Plan Expired',
        'Your Subscription was expired Please renew!',
      );
    } else {
      pref?.setBool('isLogin', true);
      Get.offNamed(RoutName.dashBoard);

    }
  }
}
