import 'package:cheminova/screens/authentication/controller/auth_service.dart';
import 'package:cheminova/screens/home_screen.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AuthController extends GetxController {
  final authService = AuthService();

  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController currentpassController = TextEditingController();
  TextEditingController newpassController = TextEditingController();
  TextEditingController confirmpassController = TextEditingController();

  RxBool isLoading = false.obs;

  Future<void> login() async {
    isLoading.value = true;
    final response = await authService.login({
      'email': emailController.text,
      'password': passwordController.text,
    });
    isLoading.value = false;
    update();
    if (response != null) {
      Get.offAll(() => const HomeScreen());
    }
  }

  Future<void> forgotpass() async{
    isLoading.value = true;
    final response = await authService.forgotPassword(
      {
        'email': emailController.text,
      }
    );
    isLoading.value = false;
    update();
    if(response != null){

    }
  }

  Future<void> changePassword() async {
    isLoading.value = true;

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString('token');

    if (token != null) {
      final response = await authService.changePassword(
        {
          'oldPassword': currentpassController.text,
          'newPassword': newpassController.text,
          'confirmPassword': confirmpassController.text,
        },
        token: token, // Pass the token here
      );
    print("tokemn ,$token");
      isLoading.value = false;
      update();

      if (response != null) {

        Get.snackbar('Success', 'Password changed successfully');
      } else {

        Get.snackbar('Error', 'Failed to change password');
      }
    } else {
      isLoading.value = false;
      update();
      Get.snackbar('Error', 'Token not found. Please login again.');
    }
  }


}
