import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; class AuthService { static const String baseUrl = 'https://api.marcoaiot.com/api'; static bool isLoggedIn = false; static Future?> loginUser(Map data) async { try { print('Sending login request with data: $data'); // Make the API call final response = await http.post( Uri.parse('$baseUrl/Auth/login'), headers: {'Content-Type': 'application/json'}, body: jsonEncode(data), ); print('Response received: ${response.body}'); if (response.statusCode == 200) { final responseData = jsonDecode(response.body); // Extract the token from the "data" field final token = responseData['data']?['token']; // Adjust based on your API response if (token != null) { // Save the token locally final prefs = await SharedPreferences.getInstance(); await prefs.setString('auth_token', token); isLoggedIn = true; return null; // No errors } else { return {'error': 'Token not found in response'}; } } else { final responseData = jsonDecode(response.body); return {'error': responseData['message'] ?? 'Invalid response from server'}; } } catch (e) { print('Unexpected error: $e'); return {'error': 'Unexpected error: $e'}; } } }