import 'package:get/get.dart';
import 'package:dio/dio.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/utils/app_snackbar.dart';
import '../../../core/utils/logger.dart';

class CompaniesManagementController extends GetxController {
  final Dio _dio = DioClient().client;

  var isLoading = true.obs;
  var companies = <Map<String, dynamic>>[].obs;

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

  Future<void> fetchCompanies() async {
    try {
      isLoading.value = true;
      final response = await _dio.get('companies');
      if (response.data['success'] == true) {
        companies.value = List<Map<String, dynamic>>.from(response.data['data']);
      }
    } catch (e) {
      AppLogger.error('Failed to fetch companies', e);
      AppSnackbar.showError('خطأ', 'تعذر تحميل قائمة الشركات');
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> updateCompany(String id, Map<String, dynamic> data) async {
    try {
      data['id'] = id;
      final response = await _dio.post('companies/update', data: data);
      if (response.data['success'] == true) {
        await fetchCompanies();
        AppSnackbar.showSuccess('نجاح', 'تم تحديث بيانات الشركة');
      }
    } catch (e) {
      AppLogger.error('Failed to update company', e);
      AppSnackbar.showError('خطأ', 'تعذر تحديث الشركة');
    }
  }

  Future<void> deleteCompany(String id) async {
    try {
      final response = await _dio.post('companies/delete', data: {'id': id});
      if (response.data['success'] == true) {
        companies.removeWhere((c) => c['id'] == id);
        AppSnackbar.showSuccess('نجاح', 'تم حذف الشركة بنجاح');
      }
    } catch (e) {
      AppLogger.error('Failed to delete company', e);
      AppSnackbar.showError('خطأ', 'تعذر حذف الشركة');
    }
  }
}
