// lib/core/networks/api_client.dart

// ignore_for_file: curly_braces_in_flow_control_structures, unused_element

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

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

class ApiSessionExpiredException implements Exception {
  const ApiSessionExpiredException();
  @override
  String toString() => 'Your session has expired. Sign in to sync changes.';
}

/// A successful write or a changed cache snapshot that screens can observe.
class ApiDataChange {
  final Uri url;
  final int revision;
  final bool isMutation;
  const ApiDataChange(this.url, this.revision, {this.isMutation = false});
}

class ApiClient {
  static String? bearerToken;
  static final Map<String, Future<void>> _backgroundRefreshes = {};
  // A late response from an older GET must not overwrite a newer snapshot.
  static final Map<String, int> _cacheRequestGenerations = {};
  static final LinkedHashMap<String, Uri> _recentApiReads = LinkedHashMap();
  static final ValueNotifier<int> offlineCacheRevision = ValueNotifier<int>(0);
  static final ValueNotifier<ApiDataChange?> dataChanges = ValueNotifier<ApiDataChange?>(null);
  static int _dataChangeSerial = 0;
  static Timer? _offlinePollTimer;
  static String? _activeOfflineScope;
  static bool _pollInFlight = false;
  static bool _sessionExpiryHandled = false;

  // ==========================================
  // 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;
          _sessionExpiryHandled = false;
          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) {
      // An invalid session must never erase the offline snapshot. Clear only
      // the credential, once, and let screens continue to render cached data.
      if (!_sessionExpiryHandled) {
        _sessionExpiryHandled = true;
        bearerToken = null;
        await DatabaseService.clearToken();
        debugPrint('AUTH: server session expired; cached data was retained.');
      }
      throw const ApiSessionExpiredException();
    }
  }

  /// Short, user-safe signal for consumers that need to distinguish an expired
  /// server session from a transport failure.
  static bool get requiresSignIn => _sessionExpiryHandled;

  /// Route families let a successful write refresh just the relevant cached
  /// reads (for example users.php after an admin/staff edit).
  static String apiFamily(Uri url) {
    final basePath = Uri.parse(baseUrl).path.replaceFirst(RegExp(r'/+$'), '');
    var path = url.path;
    if (basePath.isNotEmpty && path.startsWith(basePath)) {
      path = path.substring(basePath.length);
    }
    final parts = path.split('/').where((part) => part.isNotEmpty).toList();
    String? phpScript;
    for (final part in parts) {
      if (part.toLowerCase().endsWith('.php')) {
        phpScript = part;
        break;
      }
    }
    final route = phpScript ?? (parts.isEmpty ? path : parts.first);
    return '${url.scheme}://${url.host}:${url.hasPort ? url.port : (url.scheme == 'https' ? 443 : 80)}|$route';
  }

  static bool sameApiFamily(Uri first, Uri second) => apiFamily(first) == apiFamily(second);

  /// Call after the server confirms a write. Evicts stale cache immediately so the
  /// very next read loads fresh data instead of serving the old snapshot.
  static void announceSuccessfulMutation(Uri url) {
    // Invalidate any requests already in flight for this API family. Their
    // responses may have been read before the write was committed.
    for (final entry in _recentApiReads.entries) {
      if (sameApiFamily(entry.value, url)) {
        _cacheRequestGenerations[entry.key] =
            (_cacheRequestGenerations[entry.key] ?? 0) + 1;
      }
    }
    _publishDataChange(url, isMutation: true);
    _evictCacheForUrl(url);
    unawaited(_refreshRecentReadsForMutation(url));
  }

  static void _evictCacheForUrl(Uri changedUrl) {
    try {
      final matchingKeys = _recentApiReads.entries
          .where((entry) => sameApiFamily(entry.value, changedUrl))
          .map((entry) => entry.key)
          .toList(growable: false);

      unawaited(() async {
        try {
          await isar.writeTxn(() async {
            for (final key in matchingKeys) {
              final cached = await isar.apiCaches.filter().endpointEqualTo(key).findFirst();
              if (cached != null) {
                await isar.apiCaches.delete(cached.id);
              }
            }
            final directKey = await _offlineKey(changedUrl);
            final directCached = await isar.apiCaches.filter().endpointEqualTo(directKey).findFirst();
            if (directCached != null) {
              await isar.apiCaches.delete(directCached.id);
            }
          });
        } catch (_) {}
      }());
    } catch (_) {}
  }

  static void _publishDataChange(
    Uri url, {
    bool incrementCacheRevision = true,
    bool isMutation = false,
  }) {
    dataChanges.value = ApiDataChange(
      url,
      ++_dataChangeSerial,
      isMutation: isMutation,
    );
    if (incrementCacheRevision) offlineCacheRevision.value++;
  }

  static Future<void> _refreshRecentReadsForMutation(Uri changedUrl) async {
    if (_sessionExpiryHandled || _recentApiReads.isEmpty) return;
    try {
      final headers = await getHeaders();
      if (!(headers['Authorization'] ?? '').startsWith('Bearer ')) return;
      final matching = _recentApiReads.entries
          .where((entry) => sameApiFamily(entry.value, changedUrl))
          .toList(growable: false);
      await Future.wait(matching.map((entry) async {
        // Let a request that began before the write finish (its save is
        // generation-blocked), then start one clean post-mutation read.
        final pending = _backgroundRefreshes[entry.key];
        if (pending != null) await pending;
        await _startBackgroundRefresh(
          entry.value,
          entry.key,
          headers,
          const Duration(seconds: 5),
        );
      }));
    } catch (_) {
      // Keep the current local snapshot; the regular background poll retries.
    }
  }

  /// Call after a successful login so requests resume with the new session.
  static void markSessionRestored() => _sessionExpiryHandled = false;

  /// Account-aware key for local API snapshots. Email is stable across token
  /// refreshes; the token hash is only a fallback when profile data is absent.
  static Future<String> _offlineKey(Uri uri) async {
    var identity = '';
    try {
      final user = await DatabaseService.getLocalUser();
      identity = user?.email.trim().toLowerCase() ?? '';
    } catch (_) {}
    if (identity.isEmpty) {
      final token = (await DatabaseService.getToken()).trim();
      identity = token.isEmpty ? 'signed-out' : sha256.convert(utf8.encode(token)).toString();
    }
    final scope = sha256.convert(utf8.encode('${baseUrl}|$identity')).toString().substring(0, 24);
    if (_activeOfflineScope != scope) {
      _activeOfflineScope = scope;
      _recentApiReads.clear();
    }
    final resource = sha256.convert(utf8.encode(uri.toString()));
    return 'offline-v3:$scope:$resource';
  }

  static Future<String> _legacyOfflineKey(Uri uri) async {
    final current = await _offlineKey(uri);
    return current.replaceFirst('offline-v3:', 'offline-v2:');
  }

  static void _rememberApiRead(String cacheKey, Uri uri) {
    _recentApiReads.remove(cacheKey);
    _recentApiReads[cacheKey] = uri;
    // Only poll the most recently used resources. Polling this full set in
    // parallel keeps each open app's known data within one short refresh
    // window instead of rotating through old endpoints for several minutes.
    while (_recentApiReads.length > 16) {
      _recentApiReads.remove(_recentApiReads.keys.first);
    }
    _offlinePollTimer ??= Timer.periodic(
      const Duration(seconds: 10),
      (_) => unawaited(_pollRecentApiReads()),
    );
  }

  static Future<void> _pollRecentApiReads() async {
    if (_pollInFlight || _sessionExpiryHandled || _recentApiReads.isEmpty) return;
    if (WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed) return;
    final tokenHeaders = await getHeaders();
    if (!(tokenHeaders['Authorization'] ?? '').startsWith('Bearer ')) return;
    _pollInFlight = true;
    try {
      final entries = _recentApiReads.entries.toList(growable: false);
      final refreshes = <Future<void>>[];
      for (final entry in entries) {
        refreshes.add(_startBackgroundRefresh(
          entry.value,
          entry.key,
          tokenHeaders,
          const Duration(seconds: 5),
        ));
      }
      await Future.wait(refreshes);
    } finally {
      _pollInFlight = false;
    }
  }

  /// Immediately checks the most recently used cached API resources when the
  /// user presses the global Sync button. Existing snapshots remain available
  /// if any request fails.
  static Future<int> refreshRecentApiReads() async {
    if (_sessionExpiryHandled) {
      throw const ApiSessionExpiredException();
    }
    if (_pollInFlight) {
      final current = _backgroundRefreshes.values.toList(growable: false);
      await Future.wait(current);
      return current.length;
    }
    final headers = await getHeaders();
    if (!(headers['Authorization'] ?? '').startsWith('Bearer ')) {
      throw const ApiSessionExpiredException();
    }
    final entries = _recentApiReads.entries.toList(growable: false);
    if (entries.isEmpty) return 0;
    _pollInFlight = true;
    try {
      await Future.wait(entries.map((entry) => _startBackgroundRefresh(
            entry.value,
            entry.key,
            headers,
            const Duration(seconds: 8),
          )));
      return entries.length;
    } finally {
      _pollInFlight = false;
    }
  }

  static bool _isJsonApiResponse(http.Response response) {
    final contentType = (response.headers['content-type'] ?? '').toLowerCase();
    if (contentType.contains('json')) return true;
    final body = response.body.trimLeft();
    return body.startsWith('{') || body.startsWith('[') || body == 'null';
  }

  static int _beginCacheRequest(String cacheKey) {
    final generation = (_cacheRequestGenerations[cacheKey] ?? 0) + 1;
    _cacheRequestGenerations[cacheKey] = generation;
    return generation;
  }

  // Stream responses into a bounded buffer. `http.get` buffers the complete
  // body before returning, which can exhaust mobile memory on a runaway API
  // response. Oversized responses are rejected before JSON decoding/caching.
  static const int _maxApiResponseBytes = 8 * 1024 * 1024;

  static Future<http.Response> _boundedGet(
    Uri uri,
    Map<String, String> headers,
    Duration timeout,
  ) async {
    final client = http.Client();
    try {
      final request = http.Request('GET', uri)..headers.addAll(headers);
      final streamed = await client.send(request).timeout(timeout);
      final builder = BytesBuilder(copy: false);
      var tooLarge = false;
      await streamed.stream.forEach((chunk) {
        if (tooLarge) return;
        if (builder.length + chunk.length > _maxApiResponseBytes) {
          tooLarge = true;
          builder.takeBytes();
          return;
        }
        builder.add(chunk);
      }).timeout(timeout);
      if (tooLarge) {
        return http.Response(
          '{"detail":"The server response is larger than the safe 8 MB limit. Add API pagination or filters to load this dataset."}',
          413,
          headers: const {'content-type': 'application/json; charset=utf-8'},
          request: request,
        );
      }
      return http.Response.bytes(
        builder.takeBytes(),
        streamed.statusCode,
        headers: streamed.headers,
        request: request,
        isRedirect: streamed.isRedirect,
        persistentConnection: streamed.persistentConnection,
        reasonPhrase: streamed.reasonPhrase,
      );
    } finally {
      client.close();
    }
  }

  /// Lightweight offline-first GET for JSON API resources.
  ///
  /// If a saved copy exists it is returned immediately and a bounded network
  /// refresh updates the snapshot for the next read. Cold reads wait only for a
  /// short request timeout. Failures preserve the previous snapshot and return
  /// a consistent 503 response to existing callers.
  static Future<http.Response> offlineFirstGet(
    Uri uri, {
    Map<String, String>? headers,
    Duration timeout = const Duration(seconds: 7),
    bool forceRefresh = false,
  }) async {
    final cacheKey = await _offlineKey(uri);
    final requestHeaders = Map<String, String>.from(headers ?? const <String, String>{});
    requestHeaders.removeWhere((key, _) => key.toLowerCase() == 'authorization');
    requestHeaders.addAll(await getHeaders());
    String? savedBody;
    try {
      var saved = await isar.apiCaches.filter().endpointEqualTo(cacheKey).findFirst();
      if (saved == null) {
        final legacyKey = await _legacyOfflineKey(uri);
        saved = await isar.apiCaches.filter().endpointEqualTo(legacyKey).findFirst();
        if (saved != null && saved.jsonResponse.isNotEmpty) {
          await _saveToIsar(cacheKey, saved.jsonResponse);
        }
      }
      if (saved != null && saved.jsonResponse.isNotEmpty) savedBody = saved.jsonResponse;
    } catch (e) {
      debugPrint('OFFLINE: local snapshot lookup failed.');
    }

    if (savedBody != null && !forceRefresh) {
      if (!_sessionExpiryHandled && (requestHeaders['Authorization'] ?? '').startsWith('Bearer ')) {
        _rememberApiRead(cacheKey, uri);
        unawaited(_startBackgroundRefresh(uri, cacheKey, requestHeaders, timeout));
      }
      return http.Response(
        savedBody,
        200,
        headers: const {'content-type': 'application/json; charset=utf-8'},
        request: http.Request('GET', uri),
      );
    }

    if (_sessionExpiryHandled) {
      if (savedBody != null) {
        return http.Response(savedBody, 200,
            headers: const {'content-type': 'application/json; charset=utf-8'},
            request: http.Request('GET', uri));
      }
      return http.Response(
        '{"detail":"Your session expired. Sign in to sync new data.","offline":true}',
        401,
        headers: const {'content-type': 'application/json; charset=utf-8'},
        request: http.Request('GET', uri),
      );
    }

    try {
      if ((requestHeaders['Authorization'] ?? '').startsWith('Bearer ')) {
        _rememberApiRead(cacheKey, uri);
      }
      // A unique query value bypasses browser/proxy GET caches. Cache storage
      // still uses the stable cacheKey derived from the original URI above.
      final requestUri = forceRefresh
          ? uri.replace(queryParameters: {
              ...uri.queryParameters,
              '_refresh': DateTime.now().microsecondsSinceEpoch.toString(),
            })
          : uri;
      final requestGeneration = _beginCacheRequest(cacheKey);
      final response = await _boundedGet(requestUri, requestHeaders, timeout);
      if (response.statusCode == 200 && _isJsonApiResponse(response)) {
        await _saveToIsar(
          cacheKey,
          response.body,
          sourceUrl: uri,
          requestGeneration: requestGeneration,
        );
      } else if (response.statusCode == 403) {
        try {
          var removed = false;
          await isar.writeTxn(() async {
            final existing = await isar.apiCaches.filter().endpointEqualTo(cacheKey).findFirst();
            if (existing != null) removed = await isar.apiCaches.delete(existing.id);
          });
          if (removed) offlineCacheRevision.value++;
        } catch (_) {}
      } else if (response.statusCode == 401) {
        try {
          await handleUnauthorized(response);
        } on ApiSessionExpiredException {
          // Keep the last valid response visible when a forced refresh finds
          // an expired server session. The credential is still cleared.
        }
        if (savedBody != null) {
          return http.Response(savedBody, 200,
              headers: const {'content-type': 'application/json; charset=utf-8'},
              request: http.Request('GET', uri));
        }
      }
      if (response.statusCode >= 500 && savedBody != null) {
        return http.Response(savedBody, 200,
            headers: const {'content-type': 'application/json; charset=utf-8'},
            request: http.Request('GET', uri));
      }
      if (response.statusCode == 413 && savedBody != null) {
        // Preserve the last usable offline snapshot when a newly grown server
        // response exceeds the bounded decoder/cache size.
        return http.Response(savedBody, 200,
            headers: const {'content-type': 'application/json; charset=utf-8'},
            request: http.Request('GET', uri));
      }
      return response;
    } catch (e) {
      debugPrint('OFFLINE: initial request unavailable; no saved copy exists.');
      if (savedBody != null) {
        return http.Response(savedBody, 200,
            headers: const {'content-type': 'application/json; charset=utf-8'},
            request: http.Request('GET', uri));
      }
      return http.Response(
        '{"detail":"Offline. No saved copy is available yet.","offline":true}',
        503,
        headers: const {'content-type': 'application/json; charset=utf-8'},
        request: http.Request('GET', uri),
      );
    }
  }

  /// Reads the last saved response without starting another network request.
  /// Screens use this after a background sync notification to repaint from the
  /// newly committed snapshot without creating duplicate refreshes.
  static Future<http.Response?> cachedGet(Uri uri) async {
    try {
      final cacheKey = await _offlineKey(uri);
      var saved = await isar.apiCaches.filter().endpointEqualTo(cacheKey).findFirst();
      if (saved == null) {
        final legacyKey = await _legacyOfflineKey(uri);
        saved = await isar.apiCaches.filter().endpointEqualTo(legacyKey).findFirst();
        if (saved != null && saved.jsonResponse.isNotEmpty) {
          await _saveToIsar(cacheKey, saved.jsonResponse);
        }
      }
      if (saved == null || saved.jsonResponse.isEmpty) return null;
      return http.Response(
        saved.jsonResponse,
        200,
        headers: const {'content-type': 'application/json; charset=utf-8'},
        request: http.Request('GET', uri),
      );
    } catch (_) {
      return null;
    }
  }

  static Future<void> _startBackgroundRefresh(
    Uri uri,
    String cacheKey,
    Map<String, String> headers,
    Duration timeout,
  ) {
    final existingTask = _backgroundRefreshes[cacheKey];
    if (existingTask != null) return existingTask;
    final task = () async {
      try {
        final requestGeneration = _beginCacheRequest(cacheKey);
        final response = await _boundedGet(uri, headers, timeout);
        if (response.statusCode == 200 && _isJsonApiResponse(response)) {
          await _saveToIsar(
            cacheKey,
            response.body,
            sourceUrl: uri,
            requestGeneration: requestGeneration,
          );
        } else if (response.statusCode == 403) {
          var removed = false;
          await isar.writeTxn(() async {
            final existing = await isar.apiCaches.filter().endpointEqualTo(cacheKey).findFirst();
            if (existing != null) removed = await isar.apiCaches.delete(existing.id);
          });
          if (removed) offlineCacheRevision.value++;
        } else if (response.statusCode == 401) {
          try {
            await handleUnauthorized(response);
          } on ApiSessionExpiredException {
            // Keep the offline copy; no UI error is emitted for background sync.
          }
        }
      } catch (_) {
        // Quietly retain the last known good snapshot on network/server errors.
      } finally {
        _backgroundRefreshes.remove(cacheKey);
      }
    }();
    _backgroundRefreshes[cacheKey] = task;
    return task;
  }

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

  static Future<void> _saveToIsar(
    String endpoint,
    String body, {
    Uri? sourceUrl,
    int? requestGeneration,
  }) 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 > 3500000) {
      debugPrint('OFFLINE: large response skipped to keep local storage lightweight.');
      return; 
    }

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

    try {
      await isar.writeTxn(() async {
        if (requestGeneration != null &&
            _cacheRequestGenerations[endpoint] != requestGeneration) return;
        final previous = await isar.apiCaches.filter().endpointEqualTo(endpoint).findFirst();
        if (requestGeneration != null &&
            _cacheRequestGenerations[endpoint] != requestGeneration) return;
        contentChanged = previous == null || previous.jsonResponse != body;
        if (previous != null) newCache.id = previous.id;
        await isar.apiCaches.put(newCache);
        // Bound the shared snapshot store so a long-lived account cannot grow
        // its offline cache without limit. Recent resources stay available.
        // Keep even the number of small snapshots bounded. Query and remove
        // old entries in batches so cleanup itself cannot load an unbounded
        // cache into memory.
        var entryOverflow = (await isar.apiCaches.count()) - 128;
        while (entryOverflow > 0) {
          final oldestBatch = await isar.apiCaches
              .where()
              .sortByLastUpdated()
              .limit(16)
              .findAll();
          if (oldestBatch.isEmpty) break;
          for (final item in oldestBatch) {
            if (item.id == newCache.id) continue;
            await isar.apiCaches.delete(item.id);
            entryOverflow--;
            if (entryOverflow <= 0) break;
          }
        }

        final entries = await isar.apiCaches
            .where()
            .sortByLastUpdated()
            .limit(128)
            .findAll();
        var totalChars = entries.fold<int>(0, (sum, item) => sum + item.jsonResponse.length);
        const maxCachedChars = 24 * 1024 * 1024;
        for (final item in entries) {
          if (totalChars <= maxCachedChars) break;
          if (item.id == newCache.id) continue;
          await isar.apiCaches.delete(item.id);
          totalChars -= item.jsonResponse.length;
        }
      });
      if (contentChanged) {
        if (sourceUrl != null) {
          _publishDataChange(sourceUrl);
        } else {
          offlineCacheRevision.value++;
        }
      }
    } catch (_) {
      // A cache write must never turn a successful online response into an
      // application error.
    }
  }

  // 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');
    return offlineFirstGet(url);
  }


  // ==========================================
  // 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 uri = Uri.parse('$baseUrl/users');
      final response = await http.get(
        uri,
        headers: await getHeaders(),
      ).timeout(const Duration(seconds: 15));
      
      if (response.statusCode == 200) {
        await _saveToIsar(await _offlineKey(uri), response.body);
        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({bool refresh = false}) async {
    final uri = Uri.parse('$baseUrl/api/users.php').replace(
      queryParameters: const {'role': 'staff'},
    );

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

    final response = await offlineFirstGet(
        uri, headers: await getHeaders(), forceRefresh: refresh)
        .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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/users.php'));
    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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/users.php/$id'));
    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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/users.php/$id'));
    return true;
  }


  static Future<List<Map<String, dynamic>>> getExperts() async {
    try {
      final response = await offlineFirstGet(
        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({bool refresh = false}) async {
    final uri = Uri.parse('$baseUrl/api/admin.php/admins');
    if (kDebugMode) debugPrint('ADMIN REQUEST URL: $uri');
    final response = await offlineFirstGet(
      uri,
      headers: await getHeaders(),
      forceRefresh: refresh,
    ).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) {
        announceSuccessfulMutation(response.request?.url ?? url);
        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) {
        announceSuccessfulMutation(response.request?.url ?? url);
        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) {
        announceSuccessfulMutation(response.request?.url ?? url);
        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({bool refresh = false}) async {
    final uri = Uri.parse('$baseUrl/api/campuses.php');
    final response = await offlineFirstGet(
      uri,
      headers: await getHeaders(),
      forceRefresh: refresh,
    ).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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/campuses.php'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/campuses.php/$campusId'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/campuses.php/$campusId'));
  }

  // ==========================================
  // 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({bool refresh = false}) async {
    final uri = Uri.parse('$baseUrl/api/schools.php');
    final response = await offlineFirstGet(
        uri, headers: await getHeaders(), forceRefresh: refresh)
        .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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/schools.php'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/schools.php/$schoolId'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/schools.php/$schoolId'));
  }

  // ==========================================
  // 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({bool refresh = false}) async {
    final uri = Uri.parse('$baseUrl/api/departments.php');
    final response = await offlineFirstGet(
      uri,
      headers: await getHeaders(),
      forceRefresh: refresh,
    ).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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/departments.php'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/departments.php/$departmentId'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/departments.php/$departmentId'));
  }

  // ==========================================
  // 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({bool refresh = false}) async {
    final uri = Uri.parse('$baseUrl/api/positions.php');
    final response = await offlineFirstGet(
      uri,
      headers: await getHeaders(),
      forceRefresh: refresh,
    ).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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/positions.php'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/positions.php/$positionId'));
  }

  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});
    announceSuccessfulMutation(response.request?.url ?? Uri.parse('$baseUrl/api/positions.php/$positionId'));
  }

  // ==========================================
  // 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({bool refresh = false}) async {
    final uri = Uri.parse('$baseUrl/api/users.php/me');
    final response = await offlineFirstGet(
      uri,
      headers: await getHeaders(),
      forceRefresh: refresh,
    ).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 offlineFirstGet(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;
    }
  }
}
