// lib/core/networks/api_client.dart

// ignore_for_file: curly_braces_in_flow_control_structures, unused_element

import 'dart:convert';
import 'dart:typed_data';
import 'dart:io' show File, Platform;
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart'; // For kIsWeb and debugPrint

// --- NEW ISAR IMPORTS ---
import 'package:isar/isar.dart';
import '../models/api_cache.dart';
import '../services/database_service.dart';

class ApiClient {
  static String? bearerToken;

  // ==========================================
  // BULLETPROOF TOKEN & HEADER GENERATOR
  // ==========================================
  static Future<Map<String, String>> getHeaders() async {
    // Always synchronize the in-memory bearer token with the token stored by
    // the account that is currently signed in. This prevents an old account
    // token from surviving in memory after an admin/staff/student login switch.
    try {
      final storedToken = await DatabaseService.getToken();
      final cleanStoredToken = storedToken?.replaceAll('\"', '').trim() ?? '';

      if (cleanStoredToken.isNotEmpty && cleanStoredToken != 'null') {
        final currentToken = bearerToken?.replaceAll('\"', '').trim() ?? '';
        if (currentToken != cleanStoredToken) {
          bearerToken = cleanStoredToken;
          debugPrint('AUTH: bearer token synchronized from local storage.');
        }
      }
    } catch (e) {
      debugPrint('AUTH: unable to read stored bearer token: $e');
    }

    final cleanToken = bearerToken?.replaceAll('\"', '').trim() ?? '';

    final headers = <String, String>{
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };

    if (cleanToken.isNotEmpty && cleanToken != 'null') {
      headers['Authorization'] = 'Bearer $cleanToken';
    } else {
      debugPrint('AUTH: request sent without an authorization token.');
    }

    return headers;
  }
  
  // 1. Automatically determine the correct backend URL
 // 1. Automatically determine the correct backend URL for Pure PHP / XAMPP
  static String get baseUrl {
    // LOCAL DEVELOPMENT ADDRESSES FOR PHP (XAMPP):
    if (kIsWeb) {
      return 'https://intranet.rockviewuniversity.ac/skill_end';
    } else if (Platform.isAndroid) {
      // 10.0.2.2 is the default alias for the host machine's localhost on Android Emulators
      return 'https://intranet.rockviewuniversity.ac/skill_end';
    } else {
      // Localhost for Windows, macOS, Linux desktop apps
      return 'https://intranet.rockviewuniversity.ac/skill_end';
    }
  }

  // ==========================================
  // PROFILE PICTURE FILE STORAGE
  // ==========================================

  /// Turns a relative media path such as
  /// uploads/profile_pictures/profile_xxx.jpg into a full HTTP URL.
  /// Existing absolute URLs are returned unchanged.
  static String resolveMediaUrl(String rawPath) {
    final path = rawPath.trim();
    if (path.isEmpty) return '';
    if (path.startsWith('http://') || path.startsWith('https://')) return path;
    final normalized = path.startsWith('/') ? path.substring(1) : path;
    return '$baseUrl/$normalized';
  }

  static bool isStoredProfilePicturePath(String? rawPath) {
    if (rawPath == null) return false;
    final value = rawPath.trim().replaceAll('\\', '/');
    return value.startsWith('uploads/profile_pictures/') ||
        value.startsWith('/uploads/profile_pictures/');
  }

  /// Uploads a profile image as multipart/form-data and returns the relative
  /// server path that should be stored in PostgreSQL.
  static Future<String> uploadProfilePicture(
    Uint8List bytes, {
    required String fileName,
  }) async {
    if (bytes.isEmpty) throw ArgumentError('Profile image is empty.');

    final request = http.MultipartRequest(
      'POST',
      Uri.parse('$baseUrl/api/profile_images.php'),
    );

    // MultipartRequest must generate its own Content-Type boundary, so only
    // copy authentication/accept headers from the normal JSON header set.
    final headers = await getHeaders();
    final authorization = headers['Authorization'];
    if (authorization != null && authorization.isNotEmpty) {
      request.headers['Authorization'] = authorization;
    }
    request.headers['Accept'] = 'application/json';

    request.files.add(
      http.MultipartFile.fromBytes(
        'file',
        bytes,
        filename: fileName.trim().isEmpty ? 'profile.jpg' : fileName.trim(),
      ),
    );

    final streamed = await request.send().timeout(const Duration(seconds: 30));
    final response = await http.Response.fromStream(streamed);
    await handleUnauthorized(response);

    if (response.statusCode != 200 && response.statusCode != 201) {
      var detail = '';
      try {
        final decoded = jsonDecode(response.body);
        if (decoded is Map) {
          detail = (decoded['detail'] ?? decoded['message'] ?? decoded['error'] ?? '')
              .toString();
        }
      } catch (_) {}
      throw Exception(
        'Profile image upload failed (HTTP ${response.statusCode}). '
        '${detail.isEmpty ? "Check api/profile_images.php and uploads permissions." : detail}',
      );
    }

    final decoded = jsonDecode(response.body);
    if (decoded is! Map) {
      throw const FormatException('Profile image endpoint returned invalid JSON.');
    }
    final path = (decoded['path'] ?? decoded['profile_picture'] ?? '').toString().trim();
    if (path.isEmpty) {
      throw const FormatException('Profile image endpoint returned no file path.');
    }
    return path;
  }

  /// Removes a server-managed profile image. Base64 values and external URLs
  /// are intentionally ignored so legacy records remain safe.
  static Future<void> deleteProfilePicture(String? rawPath) async {
    if (!isStoredProfilePicturePath(rawPath)) return;

    final response = await http
        .delete(
          Uri.parse('$baseUrl/api/profile_images.php'),
          headers: await getHeaders(),
          body: jsonEncode({'path': rawPath}),
        )
        .timeout(const Duration(seconds: 15));

    await handleUnauthorized(response);
    if (response.statusCode == 200 ||
        response.statusCode == 204 ||
        response.statusCode == 404) {
      return;
    }

    var detail = '';
    try {
      final decoded = jsonDecode(response.body);
      if (decoded is Map) {
        detail = (decoded['detail'] ?? decoded['message'] ?? decoded['error'] ?? '')
            .toString();
      }
    } catch (_) {}
    throw Exception(
      'Profile image cleanup failed (HTTP ${response.statusCode}). '
      '${detail.isEmpty ? "Check api/profile_images.php." : detail}',
    );
  }

  // ==========================================
  // GLOBAL 401 SECURITY HANDLER
  // ==========================================
  
  static Future<void> handleUnauthorized(http.Response response) async {
    if (response.statusCode == 401) {
      debugPrint("🚨 401 Received from URL: ${response.request?.url}");
      debugPrint("🚨 Response Body: ${response.body}");
      
      // TEMPORARY: Comment this out while testing so it doesn't wipe your session instantly, 
      // allowing you to read the debug prints above!
      // await DatabaseService.cleanEntireDatabase();
      // bearerToken = null;
      
      throw Exception("Unauthorized request: ${response.body}");
    }
  }

  // ==========================================
  // ISAR OFFLINE-FIRST ENGINE
  // ==========================================
  
  static late Isar isar; 

  static Future<void> _saveToIsar(String endpoint, String body) async {
    // --- SAFETY VALVE ---
    // Dart strings use UTF-16, so 1 character is roughly 2 bytes.
    // 7 million characters is about 14MB, keeping us safely under Isar's 16MB limit.
    if (body.length > 7000000) {
      debugPrint('⚠️ WARNING: Response for $endpoint is too massive to cache offline (Over 14MB). Skipping Isar save.');
      return; 
    }

    final newCache = ApiCache()
      ..endpoint = endpoint
      ..jsonResponse = body
      ..lastUpdated = DateTime.now();

    await isar.writeTxn(() async {
      await isar.apiCaches.put(newCache);
    });
  }

  // This engine perfectly mimics an http.Response so NONE of your parsing or error handling codes have to be removed.
  static Future<http.Response> _smartGet(String endpointString) async {
    final url = Uri.parse('$baseUrl$endpointString');
    final headers = await getHeaders(); // 🚀 Uses async headers to guarantee token injection

    try {
      // 1. Check Isar Cache
      final cachedData = await isar.apiCaches.filter().endpointEqualTo(endpointString).findFirst();

      if (cachedData != null) {
        // 2a. Cache exists: Run network in background to update cache silently
        http.get(url, headers: headers).then((response) async {
          await handleUnauthorized(response); 
          if (response.statusCode == 200) {
            _saveToIsar(endpointString, response.body);
          }
        }).catchError((e) {
          debugPrint('Background sync failed for $endpointString: $e');
        });

        // Return a mocked HTTP 200 response containing the cached JSON so your original code remains unchanged
        return http.Response(cachedData.jsonResponse, 200);
      } else {
        // 2b. First load (no cache): Wait for network fetch and cache it immediately
        final response = await http.get(url, headers: headers);
        await handleUnauthorized(response); 
        
        if (response.statusCode == 200) {
          await _saveToIsar(endpointString, response.body);
        }
        return response;
      }
    } catch (e) {
      debugPrint('SmartGet Offline Error for $endpointString: $e');
      // Return a simulated failed response to safely trigger your existing UI error handlers
      return http.Response('{"error": "Offline and no cache available"}', 503);
    }
  }


  // ==========================================
  // NORMAL USERS (LEARNERS)
  // ==========================================
  
  static Future<bool> registerUser(Map<String, dynamic> userData) async {
    final url = Uri.parse('$baseUrl/users'); 
    
    try {
      final response = await http.post(
        url,
        headers: await getHeaders(),
        body: json.encode(userData),
      );
      
      await handleUnauthorized(response); 
      
      if (response.statusCode == 200 || response.statusCode == 201) {
        return true; 
      } else {
        debugPrint('User Registration Backend Error: ${response.statusCode} - ${response.body}');
        throw Exception(response.body);
      }
    } catch (e) {
      debugPrint('User Registration Network Error: $e');
      throw Exception(e.toString());
    }
  }

  static Future<List<Map<String, dynamic>>> getAllUsers() async {
    try {
      final response = await _smartGet('/users'); 
      if (response.statusCode == 200) {
        final dynamic data = jsonDecode(response.body);
        if (data is Map<String, dynamic> && data.containsKey('token')) ApiClient.bearerToken = data['token'];
        
        if (data is List) return List<Map<String, dynamic>>.from(data);
        else if (data is Map<String, dynamic> && data.containsKey('users')) return List<Map<String, dynamic>>.from(data['users']);
        else if (data is Map<String, dynamic> && data.containsKey('data')) return List<Map<String, dynamic>>.from(data['data']);
      }
    } catch (e) {
      debugPrint('Error fetching all users from cache: $e');
    }
    return [];
  }

  static Future<List<Map<String, dynamic>>> syncAllUsers() async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/users'), 
        headers: await getHeaders(),
      ).timeout(const Duration(seconds: 15));
      
      if (response.statusCode == 200) {
        final dynamic data = jsonDecode(response.body);
        if (data is List) return List<Map<String, dynamic>>.from(data);
        else if (data is Map<String, dynamic> && data.containsKey('users')) return List<Map<String, dynamic>>.from(data['users']);
        else if (data is Map<String, dynamic> && data.containsKey('data')) return List<Map<String, dynamic>>.from(data['data']);
      }
    } catch (e) {
      // Fail silently in background
    }
    return [];
  }

  // ==========================================
  // STAFF MANAGEMENT (Stored in Users Table)
  // ==========================================

  static Future<void> _checkStaffResponse(
    http.Response response,
    Set<int> codes,
  ) async {
    await handleUnauthorized(response);
    if (codes.contains(response.statusCode)) return;

    var detail = '';
    try {
      final data = jsonDecode(response.body);
      if (data is Map) {
        detail = (data['detail'] ?? data['message'] ?? data['error'] ?? '')
            .toString()
            .trim();
      }
    } catch (_) {}

    if (detail.length > 300) detail = '${detail.substring(0, 300)}...';

    throw Exception(
      'Staff request failed (HTTP ${response.statusCode}) at ${response.request?.url}. '
      '${detail.isEmpty ? "Check api/users.php and your session." : detail}',
    );
  }

  static Future<List<Map<String, dynamic>>> getStaff() async {
    final uri = Uri.parse('$baseUrl/api/users.php').replace(
      queryParameters: const {'role': 'staff'},
    );

    if (kDebugMode) debugPrint('STAFF REQUEST URL: $uri');

    final response = await http
        .get(uri, headers: await getHeaders())
        .timeout(const Duration(seconds: 15));

    await _checkStaffResponse(response, const {200});

    dynamic decoded;
    final cleanBody = response.body.replaceFirst('\uFEFF', '').trim();
    try {
      decoded = jsonDecode(cleanBody);
    } on FormatException catch (e) {
      if (kDebugMode) {
        var preview = cleanBody.replaceAll(RegExp(r'\s+'), ' ');
        if (preview.length > 500) preview = '${preview.substring(0, 500)}...';
        debugPrint('USERS INVALID JSON: status=${response.statusCode}, '
            'contentType=${response.headers['content-type']}, body=$preview');
        debugPrint('JSON parse error: $e');
      }
      throw const FormatException(
        'The users endpoint returned invalid JSON. Check api/users.php output.',
      );
    }

    dynamic rows = decoded;
    for (var depth = 0; rows is Map && depth < 3; depth++) {
      final envelope = rows;
      if (envelope['success'] == false || envelope['status'] == 'error') {
        throw Exception(
          'The users endpoint reported a failure: '
          '${envelope["detail"] ?? envelope["message"] ?? envelope["error"] ?? "Request unsuccessful"}',
        );
      }
      if (envelope.containsKey('users')) {
        rows = envelope['users'];
      } else if (envelope.containsKey('data')) {
        rows = envelope['data'];
      } else {
        throw const FormatException('The users response has no users/data list.');
      }
    }

    if (rows is! List) {
      throw const FormatException('The users endpoint must return a list of staff records.');
    }

    final staff = <Map<String, dynamic>>[];
    for (final item in rows) {
      if (item is! Map) {
        throw const FormatException('The users endpoint returned an invalid staff record.');
      }
      final user = item.map((key, value) => MapEntry(key.toString(), value));
      final rawRole = user['role']?.toString().trim().toLowerCase();
      // The request itself is already role=staff. If role is included, use it
      // as an extra guard; if omitted by the backend projection, trust the filter.
      if (rawRole == null || rawRole.isEmpty || rawRole == 'staff') {
        staff.add(user);
      }
    }

    if (kDebugMode) {
      debugPrint('Staff response: ${staff.length} records.');
    }
    return staff;
  }

  static Future<bool> addStaff(Map<String, dynamic> staffData) async {
    final response = await http
        .post(
          Uri.parse('$baseUrl/api/users.php'),
          headers: await getHeaders(),
          body: jsonEncode(staffData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkStaffResponse(response, const {200, 201});
    return true;
  }

  static Future<bool> updateStaff(
    int id,
    Map<String, dynamic> staffData,
  ) async {
    if (id <= 0) throw ArgumentError('Invalid staff ID.');

    final response = await http
        .put(
          Uri.parse('$baseUrl/api/users.php/$id'),
          headers: await getHeaders(),
          body: jsonEncode(staffData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkStaffResponse(response, const {200, 204});
    return true;
  }

  static Future<bool> deleteStaff(int id) async {
    if (id <= 0) throw ArgumentError('Invalid staff ID.');

    final response = await http
        .delete(
          Uri.parse('$baseUrl/api/users.php/$id'),
          headers: await getHeaders(),
        )
        .timeout(const Duration(seconds: 15));

    await _checkStaffResponse(response, const {200, 204});
    return true;
  }


  static Future<List<Map<String, dynamic>>> getExperts() async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/users/'), 
        headers: await getHeaders(),
      ).timeout(const Duration(seconds: 15));
      
      await handleUnauthorized(response); 

      if (response.statusCode == 200) {
        final dynamic decodedData = json.decode(response.body);
        if (decodedData is List) {
          return List<Map<String, dynamic>>.from(decodedData);
        } else if (decodedData is Map<String, dynamic>) {
          if (decodedData.containsKey('users')) {
            return List<Map<String, dynamic>>.from(decodedData['users']);
          } else if (decodedData.containsKey('data')) {
            return List<Map<String, dynamic>>.from(decodedData['data']);
          }
        }
        return []; 
      } else {
        debugPrint('Failed to load experts: ${response.statusCode}');
        return [];
      }
    } catch (e) {
      debugPrint('Network error fetching experts: $e');
      return [];
    }
  }

  static Future<bool> createExpert(Map<String, dynamic> expertData) async {
    final url = Uri.parse('$baseUrl/users');
    try {
      final response = await http.post(
        url,
        headers: await getHeaders(),
        body: json.encode(expertData),
      );
      
      await handleUnauthorized(response); 

      if (response.statusCode == 200 || response.statusCode == 201) {
        return true;
      } else {
        debugPrint('SERVER REJECTED DATA: ${response.statusCode}');
        return false;
      }
    } catch (e) {
      debugPrint('NETWORK ERROR: $e');
      return false;
    }
  }

  // ==========================================
  // POSTS FEED
  // ==========================================

  static Future<List<Map<String, dynamic>>> getPosts({required int limit, required int page}) async {
    try {
      final response = await _smartGet('/posts');
      if (response.statusCode == 200) {
        final List<dynamic> decodedData = json.decode(response.body);
        return List<Map<String, dynamic>>.from(decodedData); 
      } else {
        debugPrint('Failed to load posts: ${response.statusCode}');
        return [];
      }
    } catch (e) {
      debugPrint('Network error fetching posts: $e');
      return [];
    }
  }

  static Future<bool> createPost(Map<String, dynamic> postData, {File? imageFile}) async {
    final url = Uri.parse('$baseUrl/posts'); 
    try {
      var request = http.MultipartRequest('POST', url);
      final headers = await getHeaders();

      if (headers.containsKey('Authorization')) {
        request.headers['Authorization'] = headers['Authorization']!;
      }

      postData.forEach((key, value) {
        if (value != null) {
          request.fields[key] = value.toString();
        }
      });

      if (imageFile != null) {
        request.files.add(
          await http.MultipartFile.fromPath(
            'file', 
            imageFile.path,
          ),
        );
      }

      var streamedResponse = await request.send();
      var response = await http.Response.fromStream(streamedResponse);
      
      await handleUnauthorized(response); 

      if (response.statusCode == 200 || response.statusCode == 201) {
        return true; 
      } else {
        debugPrint('Create Post Backend Error: ${response.statusCode} - ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Create Post Network Error: $e');
      return false;
    }
  }

  static Future<List<Map<String, dynamic>>> getComments(int postId) async {
    try {
      final response = await _smartGet('/posts/$postId/comments');
      if (response.statusCode == 200) {
        final List<dynamic> decodedData = json.decode(response.body);
        return List<Map<String, dynamic>>.from(decodedData);
      }
      return [];
    } catch (e) {
      debugPrint('Error fetching comments: $e');
      return [];
    }
  }

 static Future<Map<String, dynamic>?> addComment(int postId, Map<String, dynamic> commentData, {File? imageFile}) async {
    final url = Uri.parse('$baseUrl/posts/$postId/comments');
    try {
      var request = http.MultipartRequest('POST', url);
      final headers = await getHeaders();
      
      if (headers.containsKey('Authorization')) {
        request.headers['Authorization'] = headers['Authorization']!;
      }

      commentData.forEach((key, value) {
        if (value != null) request.fields[key] = value.toString();
      });

      if (imageFile != null) {
        request.files.add(await http.MultipartFile.fromPath('file', imageFile.path));
      }

      var streamedResponse = await request.send();
      var response = await http.Response.fromStream(streamedResponse);
      
      await handleUnauthorized(response); 

      if (response.statusCode == 200 || response.statusCode == 201) {
        return json.decode(response.body); 
      } else {
        debugPrint('Add Comment Error: ${response.statusCode} - ${response.body}');
        return null;
      }
    } catch (e) {
      debugPrint('Error adding comment: $e');
      return null;
    }
  }

  static Future<bool> likePost(int postId) async {
    final url = Uri.parse('$baseUrl/posts/$postId/like');
    try {
      final response = await http.put(
        url,
        headers: await getHeaders(),
      );
      
      await handleUnauthorized(response);

      return response.statusCode == 200;
    } catch (e) {
      debugPrint('Like Post Network Error: $e');
      return false;
    }
  }

  // ==========================================
  // ADMINISTRATORS (STRICT LIVE FETCHING)
  // ==========================================

  static Future<List<Map<String, dynamic>>> getAdmins() async {
    final uri = Uri.parse('$baseUrl/api/admin.php/admins');
    if (kDebugMode) debugPrint('ADMIN REQUEST URL: $uri');
    final response = await http.get(
      uri,
      headers: await getHeaders(),
    ).timeout(const Duration(seconds: 15));
    await handleUnauthorized(response);

    if (response.statusCode != 200) {
      var detail = '';
      try {
        final error = jsonDecode(response.body);
        if (error is Map) {
          for (final key in ['detail', 'message', 'error']) {
            final value = error[key];
            if (value is String && value.trim().isNotEmpty) {
              detail = value.trim();
              break;
            }
          }
        }
      } catch (_) {}
      if (detail.length > 240) detail = '${detail.substring(0, 240)}...';
      throw Exception('Administrator request failed (HTTP ${response.statusCode}) at $uri. '
          '${detail.isEmpty ? "Check the administrator endpoint and session." : detail}');
    }

    dynamic rows;
    try {
      rows = jsonDecode(response.body);
    } on FormatException {
      throw const FormatException('The administrator endpoint returned invalid JSON.');
    }
    for (var depth = 0; rows is Map && depth < 3; depth++) {
      final envelope = rows;
      if (envelope['success'] == false || envelope['status'] == 'error') {
        throw Exception('The administrator endpoint reported a failure: '
            '${envelope["detail"] ?? envelope["message"] ?? envelope["error"] ?? "Request unsuccessful"}');
      }
      if (envelope.containsKey('admins')) {
        rows = envelope['admins'];
      } else if (envelope.containsKey('data')) {
        rows = envelope['data'];
      } else {
        throw const FormatException('The administrator response has no admins/data list.');
      }
    }
    if (rows is! List) {
      throw const FormatException('The administrator endpoint must return a list.');
    }
    final admins = <Map<String, dynamic>>[];
    for (final item in rows) {
      if (item is! Map) throw const FormatException('Invalid administrator record.');
      admins.add(item.map((key, value) => MapEntry(key.toString(), value)));
    }
    if (kDebugMode) debugPrint('Administrator response: ${admins.length} records.');
    return admins;
  }

  static Future<bool> addAdmin(Map<String, dynamic> adminData) async {
    final url = Uri.parse('$baseUrl/api/admin.php/admins');
    try {
      final response = await http.post(
        url,
        headers: await getHeaders(),
        body: json.encode(adminData),
      );
      
      await handleUnauthorized(response); 
      
      if (response.statusCode == 200 || response.statusCode == 201) {
        return true; 
      } else {
        debugPrint('Add Admin Backend Error: ${response.statusCode} - ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Add Admin Network Error: $e');
      return false;
    }
  }

  static Future<bool> updateAdmin(int id, Map<String, dynamic> adminData) async {
    final url = Uri.parse('$baseUrl/api/admin.php/admins/$id');
    try {
      final response = await http.put(
        url,
        headers: await getHeaders(),
        body: json.encode(adminData),
      );
      
      await handleUnauthorized(response); 
      
      if (response.statusCode == 200) {
        return true;
      } else {
        debugPrint('Update Admin Error: ${response.statusCode} - ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Update Admin Network Error: $e');
      return false;
    }
  }

  static Future<bool> deleteAdmin(int id) async {
    final url = Uri.parse('$baseUrl/api/admin.php/admins/$id');
    try {
      final response = await http.delete(
        url,
        headers: await getHeaders(),
      );
      
      await handleUnauthorized(response); 
      
      if (response.statusCode == 200 || response.statusCode == 204) {
        return true;
      } else {
        debugPrint('Delete Admin Error: ${response.statusCode} - ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Delete Admin Network Error: $e');
      return false;
    }
  }

  // ==========================================
  // EVENTS
  // ==========================================

  static Future<List<Map<String, dynamic>>> getEvents() async {
    try {
      final response = await _smartGet('/events'); 
      if (response.statusCode == 200) {
        final dynamic decodedData = json.decode(response.body);
        if (decodedData is List) {
          return List<Map<String, dynamic>>.from(decodedData);
        } else if (decodedData is Map<String, dynamic>) {
          if (decodedData.containsKey('events')) {
            return List<Map<String, dynamic>>.from(decodedData['events']);
          } else if (decodedData.containsKey('data')) {
            return List<Map<String, dynamic>>.from(decodedData['data']);
          }
        }
        return [];
      } else {
        debugPrint('Failed to load events. Status: ${response.statusCode}');
        return [];
      }
    } catch (e) {
      debugPrint('Error fetching events: $e');
      return [];
    }
  }

  static Future<bool> addEvent(Map<String, dynamic> eventData) async {
    final url = Uri.parse('$baseUrl/events'); 
    try {
      final response = await http.post(
        url,
        headers: await getHeaders(),
        body: json.encode(eventData),
      );
      
      await handleUnauthorized(response); 
      
      if (response.statusCode == 200 || response.statusCode == 201) {
        return true; 
      } else {
        debugPrint('Add Event Error: ${response.statusCode} - ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Add Event Network Error: $e');
      return false;
    }
  }

  static Future<bool> updateEvent(dynamic id, Map<String, dynamic> eventData) async {
    final url = Uri.parse('$baseUrl/events/$id'); 
    try {
      final response = await http.put(
        url,
        headers: await getHeaders(),
        body: json.encode(eventData),
      );
      
      await handleUnauthorized(response); 
      
      if (response.statusCode == 200) {
        return true;
      } else {
        debugPrint('Update Event Error: ${response.statusCode} - ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Update Event Network Error: $e');
      return false;
    }
  }
  
  static Future<bool> deleteEvent(dynamic id) async {
    final url = Uri.parse('$baseUrl/events/$id'); 
    try {
      final response = await http.delete(
        url,
        headers: await getHeaders(),
      );
      
      await handleUnauthorized(response); 
      
      if (response.statusCode == 200 || response.statusCode == 204) {
        return true;
      } else {
        debugPrint('Delete Event Error: ${response.statusCode} - ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Delete Event Network Error: $e');
      return false;
    }
  }

  // ==========================================
  // ADMIN Q&A ROUTES
  // ==========================================
  
  static Future<List<Map<String, dynamic>>> getQnaQuestions() async {
    try {
      final response = await _smartGet('/admin/qna/questions');
      if (response.statusCode == 200) {
        return List<Map<String, dynamic>>.from(json.decode(response.body));
      }
      return [];
    } catch (e) {
      debugPrint('Error fetching Q&A: $e');
      return [];
    }
  }

  static Future<bool> replyToQuestion(int questionId, Map<String, dynamic> answerData) async {
    final url = Uri.parse('$baseUrl/admin/qna/questions/$questionId/reply');
    try {
      final response = await http.post(
        url, 
        headers: await getHeaders(), 
        body: json.encode(answerData)
      );
      await handleUnauthorized(response); 
      return response.statusCode == 200;
    } catch (e) {
      debugPrint('Error posting reply: $e');
      return false;
    }
  }

  static Future<bool> deleteQuestion(int questionId) async {
    final url = Uri.parse('$baseUrl/admin/qna/questions/$questionId');
    try {
      final response = await http.delete(url, headers: await getHeaders());
      await handleUnauthorized(response); 
      return response.statusCode == 200;
    } catch (e) {
      debugPrint('Error deleting question: $e');
      return false;
    }
  }

  static Future<bool> askQuestion(Map<String, dynamic> questionData) async {
    final url = Uri.parse('$baseUrl/admin/qna/questions/ask'); 
    try {
      final response = await http.post(
        url, 
        headers: await getHeaders(), 
        body: json.encode(questionData)
      );
      
      await handleUnauthorized(response); 
      
      return response.statusCode == 200 || response.statusCode == 201;
    } catch (e) {
      debugPrint('Error asking question: $e');
      return false;
    }
  }

  // ==========================================
  // CAMPUSES
  // ==========================================

  static Future<void> _checkCampusResponse(http.Response response, Set<int> codes) async {
    await handleUnauthorized(response);
    if (codes.contains(response.statusCode)) return;
    var detail = '';
    try {
      final data = jsonDecode(response.body);
      if (data is Map) detail = (data['detail'] ?? data['message'] ?? data['error'] ?? '').toString();
    } catch (_) {}
    if (detail.length > 300) detail = '${detail.substring(0, 300)}...';
    throw Exception('Campus request failed (HTTP ${response.statusCode}) at ${response.request?.url}. '
        '${detail.isEmpty ? "Check api/campuses.php and your session." : detail}');
  }

  static Future<List<dynamic>> getCampuses() async {
    final uri = Uri.parse('$baseUrl/api/campuses.php');
    final response = await http.get(uri, headers: await getHeaders())
        .timeout(const Duration(seconds: 15));
    await _checkCampusResponse(response, const {200});
    dynamic data = jsonDecode(response.body);
    if (data is Map) {
      if (data['success'] == false || data['status'] == 'error') {
        throw Exception('Campus service rejected the request: ${data["detail"] ?? data["message"] ?? "Unknown error"}');
      }
      data = data['campuses'] ?? data['data'];
    }
    if (data is! List) throw const FormatException('Campus API must return a list.');
    return data;
  }

  static Future<void> createCampus(Map<String, dynamic> campusData) async {
    final response = await http.post(
      Uri.parse('$baseUrl/api/campuses.php'),
      headers: await getHeaders(), body: jsonEncode(campusData),
    );
    await _checkCampusResponse(response, const {200, 201});
  }

  static Future<void> updateCampus(int campusId, Map<String, dynamic> campusData) async {
    if (campusId <= 0) throw ArgumentError('Invalid campus ID.');
    final response = await http.put(
      Uri.parse('$baseUrl/api/campuses.php/$campusId'),
      headers: await getHeaders(), body: jsonEncode(campusData),
    );
    await _checkCampusResponse(response, const {200, 204});
  }

  static Future<void> deleteCampus(int campusId) async {
    if (campusId <= 0) throw ArgumentError('Invalid campus ID.');
    final response = await http.delete(
      Uri.parse('$baseUrl/api/campuses.php/$campusId'), headers: await getHeaders(),
    );
    await _checkCampusResponse(response, const {200, 204});
  }

  // ==========================================
  // SCHOOLS
  // ==========================================

  static Future<void> _checkSchoolResponse(http.Response response, Set<int> codes) async {
    await handleUnauthorized(response);
    if (codes.contains(response.statusCode)) return;

    var detail = '';
    try {
      final data = jsonDecode(response.body);
      if (data is Map) {
        detail = (data['detail'] ?? data['message'] ?? data['error'] ?? '').toString();
      }
    } catch (_) {}

    if (detail.length > 300) detail = '${detail.substring(0, 300)}...';

    throw Exception(
      'School request failed (HTTP ${response.statusCode}) at ${response.request?.url}. '
      '${detail.isEmpty ? "Check api/schools.php and your session." : detail}',
    );
  }

  static Future<List<dynamic>> getSchools() async {
    final uri = Uri.parse('$baseUrl/api/schools.php');
    final response = await http
        .get(uri, headers: await getHeaders())
        .timeout(const Duration(seconds: 15));

    await _checkSchoolResponse(response, const {200});

    dynamic data = jsonDecode(response.body);
    if (data is Map) {
      if (data['success'] == false || data['status'] == 'error') {
        throw Exception(
          'School service rejected the request: '
          '${data["detail"] ?? data["message"] ?? "Unknown error"}',
        );
      }
      data = data['schools'] ?? data['data'];
    }

    if (data is! List) {
      throw const FormatException('School API must return a list.');
    }

    return data;
  }

  static Future<void> createSchool(Map<String, dynamic> schoolData) async {
    final response = await http
        .post(
          Uri.parse('$baseUrl/api/schools.php'),
          headers: await getHeaders(),
          body: jsonEncode(schoolData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkSchoolResponse(response, const {200, 201});
  }

  static Future<void> updateSchool(
    int schoolId,
    Map<String, dynamic> schoolData,
  ) async {
    if (schoolId <= 0) throw ArgumentError('Invalid school ID.');

    final response = await http
        .put(
          Uri.parse('$baseUrl/api/schools.php/$schoolId'),
          headers: await getHeaders(),
          body: jsonEncode(schoolData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkSchoolResponse(response, const {200, 204});
  }

  static Future<void> deleteSchool(int schoolId) async {
    if (schoolId <= 0) throw ArgumentError('Invalid school ID.');

    final response = await http
        .delete(
          Uri.parse('$baseUrl/api/schools.php/$schoolId'),
          headers: await getHeaders(),
        )
        .timeout(const Duration(seconds: 15));

    await _checkSchoolResponse(response, const {200, 204});
  }

  // ==========================================
  // DEPARTMENTS
  // ==========================================

  static Future<void> _checkDepartmentResponse(
    http.Response response,
    Set<int> codes,
  ) async {
    await handleUnauthorized(response);
    if (codes.contains(response.statusCode)) return;

    var detail = '';
    try {
      final data = jsonDecode(response.body);
      if (data is Map) {
        detail = (data['detail'] ?? data['message'] ?? data['error'] ?? '')
            .toString();
      }
    } catch (_) {}

    if (detail.length > 300) detail = '${detail.substring(0, 300)}...';

    throw Exception(
      'Department request failed (HTTP ${response.statusCode}) at ${response.request?.url}. '
      '${detail.isEmpty ? "Check api/departments.php and your session." : detail}',
    );
  }

  static Future<List<dynamic>> getDepartments() async {
    final uri = Uri.parse('$baseUrl/api/departments.php');
    final response = await http
        .get(uri, headers: await getHeaders())
        .timeout(const Duration(seconds: 15));

    await _checkDepartmentResponse(response, const {200});

    dynamic data = jsonDecode(response.body);
    if (data is Map) {
      if (data['success'] == false || data['status'] == 'error') {
        throw Exception(
          'Department service rejected the request: '
          '${data["detail"] ?? data["message"] ?? "Unknown error"}',
        );
      }
      data = data['departments'] ?? data['data'];
    }

    if (data is! List) {
      throw const FormatException('Department API must return a list.');
    }

    return data;
  }

  static Future<void> createDepartment(
    Map<String, dynamic> departmentData,
  ) async {
    final response = await http
        .post(
          Uri.parse('$baseUrl/api/departments.php'),
          headers: await getHeaders(),
          body: jsonEncode(departmentData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkDepartmentResponse(response, const {200, 201});
  }

  static Future<void> updateDepartment(
    int departmentId,
    Map<String, dynamic> departmentData,
  ) async {
    if (departmentId <= 0) throw ArgumentError('Invalid department ID.');

    final response = await http
        .put(
          Uri.parse('$baseUrl/api/departments.php/$departmentId'),
          headers: await getHeaders(),
          body: jsonEncode(departmentData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkDepartmentResponse(response, const {200, 204});
  }

  static Future<void> deleteDepartment(int departmentId) async {
    if (departmentId <= 0) throw ArgumentError('Invalid department ID.');

    final response = await http
        .delete(
          Uri.parse('$baseUrl/api/departments.php/$departmentId'),
          headers: await getHeaders(),
        )
        .timeout(const Duration(seconds: 15));

    await _checkDepartmentResponse(response, const {200, 204});
  }

  // ==========================================
  // POSITIONS (MANAGEMENT ENDPOINTS)
  // ==========================================

  static Future<void> _checkPositionResponse(
    http.Response response,
    Set<int> codes,
  ) async {
    await handleUnauthorized(response);
    if (codes.contains(response.statusCode)) return;

    var detail = '';
    try {
      final data = jsonDecode(response.body);
      if (data is Map) {
        detail = (data['detail'] ?? data['message'] ?? data['error'] ?? '')
            .toString();
      }
    } catch (_) {}

    if (detail.length > 300) detail = '${detail.substring(0, 300)}...';

    throw Exception(
      'Position request failed (HTTP ${response.statusCode}) at ${response.request?.url}. '
      '${detail.isEmpty ? "Check api/positions.php and your session." : detail}',
    );
  }

  static Future<List<dynamic>> getPositions() async {
    final uri = Uri.parse('$baseUrl/api/positions.php');
    final response = await http
        .get(uri, headers: await getHeaders())
        .timeout(const Duration(seconds: 15));

    await _checkPositionResponse(response, const {200});

    dynamic data = jsonDecode(response.body);
    if (data is Map) {
      if (data['success'] == false || data['status'] == 'error') {
        throw Exception(
          'Position service rejected the request: '
          '${data["detail"] ?? data["message"] ?? "Unknown error"}',
        );
      }
      data = data['positions'] ?? data['data'];
    }

    if (data is! List) {
      throw const FormatException('Position API must return a list.');
    }

    return data;
  }

  static Future<void> createPosition(Map<String, dynamic> positionData) async {
    final response = await http
        .post(
          Uri.parse('$baseUrl/api/positions.php'),
          headers: await getHeaders(),
          body: jsonEncode(positionData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkPositionResponse(response, const {200, 201});
  }

  static Future<void> updatePosition(
    int positionId,
    Map<String, dynamic> positionData,
  ) async {
    if (positionId <= 0) throw ArgumentError('Invalid position ID.');

    final response = await http
        .put(
          Uri.parse('$baseUrl/api/positions.php/$positionId'),
          headers: await getHeaders(),
          body: jsonEncode(positionData),
        )
        .timeout(const Duration(seconds: 15));

    await _checkPositionResponse(response, const {200, 204});
  }

  static Future<void> deletePosition(int positionId) async {
    if (positionId <= 0) throw ArgumentError('Invalid position ID.');

    final response = await http
        .delete(
          Uri.parse('$baseUrl/api/positions.php/$positionId'),
          headers: await getHeaders(),
        )
        .timeout(const Duration(seconds: 15));

    await _checkPositionResponse(response, const {200, 204});
  }

  // ==========================================
  // LIBRARY MANAGEMENT ENDPOINTS
  // ==========================================

  // 🚀 UPGRADED TO SMARTGET: Instant offline loading for Library Dashboard
  static Future<Map<String, dynamic>> getLibraryDashboardStats() async {
    try {
      final response = await _smartGet('/library/stats'); 

      await handleUnauthorized(response);

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to load dashboard statistics');
      }
    } catch (e) {
      debugPrint('Library Stats Network Error: $e');
      throw Exception('Failed to load dashboard statistics: $e');
    }
  }

  // 🚀 UPGRADED TO SMARTGET: Instant offline loading for Books Directory
  static Future<List<Map<String, dynamic>>> getBooks() async {
    try {
      final response = await _smartGet('/library/books'); 

      await handleUnauthorized(response);

      if (response.statusCode == 200) {
        final dynamic data = jsonDecode(response.body);
        if (data is List) {
          return List<Map<String, dynamic>>.from(data);
        } else if (data is Map<String, dynamic> && data.containsKey('data')) {
          return List<Map<String, dynamic>>.from(data['data']);
        }
        return [];
      } else {
        throw Exception('Failed to load books. Status: ${response.statusCode}');
      }
    } catch (e) {
      debugPrint('Error fetching books: $e');
      throw Exception('Failed to load books');
    }
  }

  // 🚀 UPGRADED TO SMARTGET: Instant offline loading for Borrowing Records
  static Future<List<Map<String, dynamic>>> getBorrowRecords() async {
    try {
      final response = await _smartGet('/library/borrow-records'); 

      await handleUnauthorized(response);

      if (response.statusCode == 200) {
        final dynamic data = jsonDecode(response.body);
        if (data is List) {
          return List<Map<String, dynamic>>.from(data);
        } else if (data is Map<String, dynamic> && data.containsKey('data')) {
          return List<Map<String, dynamic>>.from(data['data']);
        }
        return [];
      } else {
        throw Exception('Failed to load borrowing records. Status: ${response.statusCode}');
      }
    } catch (e) {
      debugPrint('Error fetching borrowing records: $e');
      throw Exception('Failed to load borrowing records');
    }
  }

  // 🚀 UPGRADED TO SMARTGET: Instant offline loading for Students Directory
  static Future<List<Map<String, dynamic>>> getStudents() async {
    try {
      final response = await _smartGet('/library/students'); 

      await handleUnauthorized(response);

      if (response.statusCode == 200) {
        final dynamic data = jsonDecode(response.body);
        if (data is List) {
          return List<Map<String, dynamic>>.from(data);
        } else if (data is Map<String, dynamic> && data.containsKey('data')) {
          return List<Map<String, dynamic>>.from(data['data']);
        }
        return [];
      } else {
        throw Exception('Failed to load students. Status: ${response.statusCode}');
      }
    } catch (e) {
      debugPrint('Error fetching students: $e');
      throw Exception('Failed to load students');
    }
  }
  
  // ==========================================
  // CURRENT SIGNED-IN USER
  // ==========================================

  /// Retrieves the authoritative database record for the account that owns
  /// the current opaque bearer session token. The server resolves the token;
  /// Flutter never attempts to decode or guess user identity from it.
  static Future<Map<String, dynamic>> getCurrentLoggedInUser() async {
    final uri = Uri.parse('$baseUrl/api/users.php/me');
    final response = await http.get(
      uri,
      headers: await getHeaders(),
    ).timeout(const Duration(seconds: 15));

    await handleUnauthorized(response);

    if (response.statusCode != 200) {
      var detail = '';
      try {
        final decoded = jsonDecode(response.body);
        if (decoded is Map) {
          detail = (decoded['detail'] ?? decoded['message'] ?? decoded['error'] ?? '')
              .toString()
              .trim();
        }
      } catch (_) {}

      throw Exception(
        'Unable to retrieve the signed-in account (HTTP ${response.statusCode}). '
        '${detail.isEmpty ? "Please sign in again and check api/users.php/me." : detail}',
      );
    }

    dynamic decoded;
    try {
      decoded = jsonDecode(response.body);
    } on FormatException {
      throw const FormatException('The signed-in account endpoint returned invalid JSON.');
    }

    if (decoded is Map && decoded['user'] is Map) {
      decoded = decoded['user'];
    } else if (decoded is Map && decoded['data'] is Map) {
      decoded = decoded['data'];
    }

    if (decoded is! Map) {
      throw const FormatException('The signed-in account endpoint did not return a user object.');
    }

    final user = decoded.map((key, value) => MapEntry(key.toString(), value));
    final id = int.tryParse(user['id']?.toString() ?? '');
    final fullName = (user['full_name'] ?? user['fullName'] ?? '').toString().trim();
    final email = (user['email'] ?? '').toString().trim();

    if (id == null || id <= 0 || fullName.isEmpty || email.isEmpty) {
      throw const FormatException(
        'The signed-in database account is missing id, full_name, or email.',
      );
    }

    return Map<String, dynamic>.from(user);
  }

  // ==========================================
  // STAFF / LECTURER REPORTING
  // ==========================================

  static Future<int?> createStaffReport(Map<String, dynamic> reportData) async {
    final uri = Uri.parse('$baseUrl/api/staff_reports.php');
    final response = await http.post(
      uri,
      headers: await getHeaders(),
      body: jsonEncode(reportData),
    ).timeout(const Duration(seconds: 15));

    await handleUnauthorized(response);

    if (response.statusCode != 200 && response.statusCode != 201) {
      var detail = '';
      try {
        final decoded = jsonDecode(response.body);
        if (decoded is Map) {
          detail = (decoded['detail'] ?? decoded['message'] ?? decoded['error'] ?? '').toString().trim();
        }
      } catch (_) {}
      throw Exception(
        'Lecturer report failed (HTTP ${response.statusCode}). '
        '${detail.isEmpty ? "Check api/staff_reports.php and the database connection." : detail}',
      );
    }

    if (response.body.trim().isEmpty) return null;
    try {
      final decoded = jsonDecode(response.body);
      if (decoded is Map && decoded['id'] != null) {
        return int.tryParse(decoded['id'].toString());
      }
    } catch (_) {}
    return null;
  }

  static Future<List<Map<String, dynamic>>> getStaffReports({int? lecturerId}) async {
    var uri = Uri.parse('$baseUrl/api/staff_reports.php');
    if (lecturerId != null && lecturerId > 0) {
      uri = uri.replace(queryParameters: {'lecturer_id': lecturerId.toString()});
    }

    final response = await http.get(uri, headers: await getHeaders())
        .timeout(const Duration(seconds: 15));
    await handleUnauthorized(response);

    if (response.statusCode != 200) {
      throw Exception('Failed to load lecturer reports (HTTP ${response.statusCode}).');
    }

    final decoded = jsonDecode(response.body);
    if (decoded is! List) {
      throw const FormatException('Lecturer reports endpoint must return a list.');
    }
    return decoded
        .whereType<Map>()
        .map((row) => row.map((key, value) => MapEntry(key.toString(), value)))
        .toList();
  }

  // --- Q&A / SUPPORT FORUM ---
  
  static Future<bool> answerQuestion(int questionId, Map<String, dynamic> answerData) async {
    try {
      final url = Uri.parse('$baseUrl/qna/$questionId/answers'); 
      final response = await http.post(
        url,
        headers: await getHeaders(),
        body: jsonEncode(answerData),
      );

      if (response.statusCode == 200 || response.statusCode == 201) {
        return true;
      } else {
        debugPrint('Failed to answer question. Status code: ${response.statusCode}');
        debugPrint('Response: ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Error answering question: $e');
      return false;
    }
  }
}