// lib/core/networks/api_admin.dart

import 'dart:convert';
import 'dart:io' show Platform; // Added for platform checking
import 'package:flutter/foundation.dart'; // For kIsWeb and debugPrint
import 'package:http/http.dart' as http;
import 'api_client.dart'; // Allows access to the shared Bearer token

class ApiAdmin {
  // 1. Automatically determine the correct backend URL for PHP/XAMPP
  static String get baseUrl {
    // PAUSED LIVE URL:
    // return 'https://smartschool.ac.zm/api';

    // LOCAL DEVELOPMENT ADDRESSES (XAMPP):
    if (kIsWeb) {
      return 'http://localhost/skill_end/api';
    } else if (Platform.isAndroid) {
      // 10.0.2.2 is the default alias for the host machine's localhost on Android Emulators
      // (Change this to your IPv4 address e.g., 'http://192.168.x.x/skill_end/api' if using a physical Android device)
      return 'http://10.0.2.2/skill_end/api';
    } else {
      // Localhost for Windows, macOS, Linux desktop apps
      return 'http://localhost/skill_end/api';
    }
  }

  // Helper method to inject headers and the Bearer token into every request
  static Map<String, String> get _headers {
    return {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      if (ApiClient.bearerToken != null)
        'Authorization': 'Bearer ${ApiClient.bearerToken}',
    };
  }

  // ============================================================================
  // ANNOUNCEMENTS MANAGEMENT
  // ============================================================================

  /// Fetch all announcements for the admin history feed
  static Future<dynamic> getAnnouncements() async {
    try {
      // 🚀 Explicitly targeting the announcements.php file
      final url = Uri.parse('$baseUrl/announcements.php');
      
      final response = await http.get(url, headers: _headers);
      
      if (response.statusCode == 200) {
        final decoded = jsonDecode(response.body);
        return decoded; 
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      debugPrint('Error getting announcements: $e');
      rethrow; 
    }
  }

  /// Publish a new announcement to a specific campus or all campuses
  static Future<bool> createAnnouncement(Map<String, dynamic> payload) async {
    try {
      // 🚀 Explicitly targeting the announcements.php file
      final url = Uri.parse('$baseUrl/announcements.php');
      final response = await http.post(
        url,
        headers: _headers,
        body: jsonEncode(payload),
      );

      // 200 OK or 201 Created
      if (response.statusCode == 200 || response.statusCode == 201) {
        return true;
      } else {
        debugPrint('Failed to create announcement: ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Error creating announcement: $e');
      return false;
    }
  }

  /// Delete an existing announcement by its database ID
  static Future<bool> deleteAnnouncement(int id) async {
    try {
      // 🚀 Passes the ID using PATH_INFO to match the PHP router
      final url = Uri.parse('$baseUrl/announcements.php/$id');
      final response = await http.delete(url, headers: _headers);

      // 200 OK or 204 No Content
      if (response.statusCode == 200 || response.statusCode == 204) {
        return true;
      } else {
        debugPrint('Failed to delete announcement: ${response.body}');
        return false;
      }
    } catch (e) {
      debugPrint('Error deleting announcement: $e');
      return false;
    }
  }
}