import 'dart:convert';
import 'package:http/http.dart' as http;

import '../config/api_config.dart';
import '../models/user_settings.dart';
import '../models/school_settings.dart';

class SettingsApi {
  static Map<String, String> _headers(String token) => {
    'Accept': 'application/json',
    'Authorization': 'Bearer $token',
  };

  static Future<UserSettings> fetchUserSettings({required String token}) async {
    final uri = Uri.parse('${ApiConfig.phpApiBase}/api_user_settings.php');
    final res = await http.get(uri, headers: _headers(token));

    final data = jsonDecode(res.body) as Map<String, dynamic>;
    if (res.statusCode != 200 || data['success'] != true) {
      throw Exception(data['message'] ?? 'User settings error');
    }

    return UserSettings.fromMap(
      (data['settings'] as Map).cast<String, dynamic>(),
    );
  }

  static Future<SchoolSettings> fetchSchoolSettings({
    required String token,
    required int schoolId,
  }) async {
    final uri = Uri.parse(
      '${ApiConfig.phpApiBase}/api_school_settings.php?school_id=$schoolId',
    );
    final res = await http.get(uri, headers: _headers(token));

    final data = jsonDecode(res.body) as Map<String, dynamic>;
    if (res.statusCode != 200 || data['success'] != true) {
      throw Exception(data['message'] ?? 'School settings error');
    }

    return SchoolSettings.fromMap(
      (data['settings'] as Map).cast<String, dynamic>(),
    );
  }
}
