// lib/core/networks/api_admin.dart

import 'dart:convert';
import 'package:flutter/foundation.dart'; // For 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 => '${ApiClient.baseUrl}/api';

  // ============================================================================
  // 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 ApiClient.offlineFirstGet(
        url,
        headers: await ApiClient.getHeaders(),
      );
      
      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: await ApiClient.getHeaders(),
        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: await ApiClient.getHeaders());

      // 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;
    }
  }
}
