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

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class RegisterController extends GetxController {
  final firstName = TextEditingController();
  final lastName = TextEditingController();
  final email = TextEditingController();
  final phone = TextEditingController();
  final password = TextEditingController();
  
  final FlutterSecureStorage storage = const FlutterSecureStorage();
  final formKey = GlobalKey<FormState>();

  var isLoading = false.obs;

  void register() async {
    if (formKey.currentState!.validate()) {
      isLoading.value = true;
      
      // الحصول على البصمة
      String fingerprint = await DeviceHelper.getDeviceFingerprint();
      
      var payload = {
        "first_name": firstName.text,
        "last_name": lastName.text,
        "email": email.text,
        "phone": phone.text,
        "password": password.text,
        "fingerprint": fingerprint,
      };

      Log.print('🚀 Register Payload: $payload');
      var res = await CRUD().post(link: AppLink.register, payload: payload);
      Log.print('📥 Register Response: $res');

      isLoading.value = false;

      if (res != 'failure' && res is Map && res['status'] == 'success') {
        // حفظ كلمة المرور للدخول التلقائي لاحقاً
        await storage.write(key: 'password', value: password.text);
        
        Get.defaultDialog(

          title: "نجاح",
          middleText: res['message']['message'] ?? "تم تقديم طلبك بنجاح. يرجى انتظار موافقة الإدارة.",
          onConfirm: () {
            Get.back(); // close dialog
            Get.back(); // return to login
          },
          textConfirm: "موافق",
        );
      } else {
        Get.snackbar(
          "خطأ",
          res is Map ? res['message'].toString() : "فشل تقديم طلب التسجيل",
          backgroundColor: Colors.red.withOpacity(0.7),
          colorText: Colors.white,
        );
      }
    }
  }

  @override
  void onClose() {
    firstName.dispose();
    lastName.dispose();
    email.dispose();
    phone.dispose();
    password.dispose();
    super.onClose();
  }
}
