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

class ApiService {
  // English: Client instance to perform network requests.
  // Arabic: نسخة العميل لإجراء طلبات الشبكة.
  final http.Client _client = http.Client();

  // English: Perform a login request with email and password parameters.
  // Arabic: تنفيذ طلب تسجيل الدخول باستخدام معلمات البريد الإلكتروني وكلمة المرور.
  Future<http.Response> login(String email, String password) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.loginEndpoint}');
    
    // English: Send POST request containing JSON body to login endpoint.
    // Arabic: إرسال طلب من نوع بوست يحتوي على نص جيسون إلى نقطة تسجيل الدخول.
    return await _client.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: jsonEncode({
        'email': email,
        'password': password,
      }),
    );
  }

  // English: Fetch current user details by supplying the JWT token.
  // Arabic: جلب تفاصيل المستخدم الحالي من خلال توفير رمز التحقق.
  Future<http.Response> getMe(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.meEndpoint}');

    // English: Send GET request with authorization token header.
    // Arabic: إرسال طلب من نوع غيت مع ترويسة رمز التفويض.
    return await _client.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Fetch WhatsApp connection status.
  // Arabic: جلب حالة اتصال الواتساب.
  Future<http.Response> getWhatsAppStatus(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.whatsappStatusEndpoint}');
    return await _client.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Fetch subscription plans list.
  // Arabic: جلب قائمة باقات الاشتراك.
  Future<http.Response> getPlans(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.plansEndpoint}');
    return await _client.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Fetch CRM contacts directory.
  // Arabic: جلب دليل جهات الاتصال الخاص بنظام إدارة العملاء.
  Future<http.Response> getContacts(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.contactsEndpoint}');
    return await _client.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Create a new contact in CRM directory.
  // Arabic: إنشاء جهة اتصال جديدة في دليل إدارة العملاء.
  Future<http.Response> addContact(String token, String name, String phone) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.contactsEndpoint}');
    return await _client.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
      body: jsonEncode({
        'name': name,
        'phone': phone,
      }),
    );
  }

  // English: Fetch chatbot rules.
  // Arabic: جلب قواعد الرد الآلي لروبوت الدردشة.
  Future<http.Response> getChatbotRules(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.chatbotRulesEndpoint}');
    return await _client.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Fetch Super Admin platform statistics.
  // Arabic: جلب إحصائيات منصة المشرف العام.
  Future<http.Response> getAdminStats(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.adminStatsEndpoint}');
    return await _client.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Request a new WhatsApp QR connection.
  // Arabic: طلب اتصال واتساب جديد برمز استجابة سريع.
  Future<http.Response> requestWhatsAppQr(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.whatsappQrEndpoint}');
    return await _client.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Disconnect the active WhatsApp connection session.
  // Arabic: قطع اتصال جلسة الواتساب النشطة.
  Future<http.Response> disconnectWhatsApp(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.whatsappDisconnectEndpoint}');
    return await _client.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Approve a pending company subscription billing.
  // Arabic: الموافقة على اشتراك فوترة الشركة المعلق.
  Future<http.Response> approveBilling(String token, int companyId) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.approveBillingEndpoint}');
    return await _client.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
      body: jsonEncode({
        'company_id': companyId,
      }),
    );
  }

  // English: Fetch Meta sessions connection status.
  Future<http.Response> getMetaSessions(String token) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.metaSessionsEndpoint}');
    return await _client.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );
  }

  // English: Connect a new Facebook page or Instagram channel.
  Future<http.Response> connectMetaSession(String token, String channelType, String pageId, String pageName, String pageAccessToken) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.metaConnectEndpoint}');
    return await _client.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
      body: jsonEncode({
        'channel_type': channelType,
        'page_id': pageId,
        'page_name': pageName,
        'page_access_token': pageAccessToken,
      }),
    );
  }

  // English: Disconnect a Meta page or Instagram channel.
  Future<http.Response> disconnectMetaSession(String token, int sessionId) async {
    final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.metaDisconnectEndpoint}');
    return await _client.delete(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      },
      body: jsonEncode({
        'session_id': sessionId,
      }),
    );
  }
}
