import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'LoginApi.dart'; // To reuse baseUrl if needed, or define locally

class GajiApi {
  // Gunakan baseUrl yang sama dengan LoginApi
  static const String baseUrl = 'https://ta.myhost.id/E31230906/api';

  static const Duration timeoutDuration = Duration(seconds: 30);

  Future<String?> _getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString('access_token');
  }

  Future<int?> _getIdTeknisi() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getInt('id_teknisi');
  }

  Future<Map<String, dynamic>> getRiwayat() async {
    try {
      final token = await _getToken();
      final idTeknisi = await _getIdTeknisi();
      
      final response = await http.get(
        Uri.parse('$baseUrl/gaji/riwayat?id_teknisi=$idTeknisi'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(timeoutDuration);
      
      return jsonDecode(response.body);
    } catch (e) { 
      return {'success': false, 'message': e.toString()}; 
    }
  }

  Future<Map<String, dynamic>> getDetail(int id) async {
    try {
      final token = await _getToken();
      final idTeknisi = await _getIdTeknisi();
      
      final response = await http.get(
        Uri.parse('$baseUrl/gaji/$id?id_teknisi=$idTeknisi'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(timeoutDuration);
      
      return jsonDecode(response.body);
    } catch (e) { 
      return {'success': false, 'message': e.toString()}; 
    }
  }
}
