import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:service/constant/links.dart';
import 'package:service/controller/functions/crud.dart';

import '../views/home/main.dart';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class LoginController extends GetxController {
  var email = TextEditingController();
  var password = TextEditingController();
  final formKey = GlobalKey<FormState>();

  // Use FlutterSecureStorage instead of GetStorage
  final FlutterSecureStorage storage = const FlutterSecureStorage();

  void login() async {
    String? storedEmail = await storage.read(key: 'email');
    String? storedPassword = await storage.read(key: 'password');

    if (storedEmail != null) {
      Get.off(() => Main());
    } else {
      if (formKey.currentState!.validate()) {
        var res = await CRUD().get(link: AppLink.login, payload: {
          "email": storedEmail ?? email.text,
          "password": storedPassword ?? password.text,
        });

        if (res != 'failure') {
          var d = jsonDecode(res);
          if (d['message'] == "Login successful") {
            // Save data securely in FlutterSecureStorage
            await storage.write(key: 'email', value: d['data']['email']);
            await storage.write(key: 'name', value: d['data']['first_name']);
            await storage.write(key: 'driverID', value: d['data']['id']);
            await storage.write(key: 'password', value: password.text);

            Get.off(() => Main());
          }
        }
      }
    }
  }
}
