import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:inventory_system/services/api_service.dart';
import 'package:inventory_system/services/session_manager.dart';

class SupplierService {

  Future<List<dynamic>> fetchSuppliers() async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/SupplierList');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Fetching suppliers from: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(uri, headers: headers);

      debugPrint('SupplierList API Response Status: ${response.statusCode}');
      debugPrint('SupplierList API Response Body: ${response.body}');

      if (response.statusCode == 200) {
        if (response.body.isNotEmpty) {
          return jsonDecode(response.body);
        } else {
          return [];
        }
      } else {
        throw Exception(
            'Failed to load suppliers. Status code: ${response.statusCode}');
      }
    } on SocketException {
      throw Exception('No Internet connection. Please check your network.');
    } catch (e) {
      debugPrint('Error fetching suppliers: $e');
      rethrow;
    }
  }

  Future<void> addSupplier(Map<String, dynamic> supplierData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/AddSupplier');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Adding supplier to: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(
        uri,
        headers: headers,
        body: jsonEncode(supplierData),
      );

      if (response.statusCode != 200) {
        throw Exception(
            'Failed to add supplier. Status code: ${response.statusCode}');
      }
    } on SocketException {
      throw Exception('No Internet connection. Please check your network.');
    } catch (e) {
      debugPrint('Error adding supplier: $e');
      rethrow;
    }
  }

  Future<void> updateSupplier(Map<String, dynamic> supplierData) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/EditSupplier');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Updating supplier at: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.post(
        uri,
        headers: headers,
        body: jsonEncode(supplierData),
      );

      if (response.statusCode != 200) {
        throw Exception(
            'Failed to update supplier. Status code: ${response.statusCode}');
      }
    } on SocketException {
      throw Exception('No Internet connection. Please check your network.');
    } catch (e) {
      debugPrint('Error updating supplier: $e');
      rethrow;
    }
  }

  Future<void> deleteSupplier(int id) async {
    final uri = Uri.parse('${ApiService.baseUrl}/InvMainAPI/DeleteSupplier/$id');
    final cookie = SessionManager.instance.getCookie();
    debugPrint("Deleting supplier at: $uri");

    final Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      if (cookie != null) 'Cookie': cookie,
    };

    try {
      final response = await http.delete(uri, headers: headers);

      if (response.statusCode != 200) {
        throw Exception(
            'Failed to delete supplier. Status code: ${response.statusCode}');
      }
    } on SocketException {
      throw Exception('No Internet connection. Please check your network.');
    } catch (e) {
      debugPrint('Error deleting supplier: $e');
      rethrow;
    }
  }
}
