import 'dart:convert';

import 'package:cheminova/models/rd_placed_order_model.dart';
import 'package:cheminova/utils/api_urls.dart';
import 'package:cheminova/utils/show_snackbar.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import '../models/rd_order_item_model.dart';


class RDOrderPlacedService {
  final Dio _dio = Dio(); // Create Dio instance

  Future<void> placRDeOrder(PlacedOrdersProcessing orderDetails,
      String token) async {
    //try {
    // logger.w("orderjson ${jsonEncode(orderDetails.toJson())}");
    final response = await _dio.post(
      'https://api.cnapp.co.in/api/pd-process-order',
      // Ensure this is your correct endpoint
      data: jsonEncode(orderDetails.toJson()),
      options: Options(
        headers: {
          'Authorization': 'Bearer $token',
          'Content-Type': 'application/json',
        },
      ),
    );
    //logger.w("Status code,${response.statusCode}");
    if (response.statusCode != 200) {
      showSnackbar("stock not Available");
      throw Exception('Failed to RD place order');
    }
    //  else if(response.statusCode != 200 && response.statusCode == 400){
    //    showSnackbar("stock not Available");
    // }
  }

  Future<void> RDOrderCancel(String token, String orderId, String reason) async {
    try {
      // Correct API URL with orderId passed in the URL
      final String url = 'https://api.cnapp.co.in/api/pd-cancel-order/$orderId';

      // Make the PUT request
      final response = await _dio.put(
        url, // Use the correct URL here
        data: {
          "cancellationReason": reason, // Send the cancellation reason as JSON
        },
        options: Options(
          headers: {
            'Authorization': 'Bearer $token', // Pass the token in the Authorization header
            'Content-Type': 'application/json', // Set content-type to application/json
          },
        ),
      );

      // Check the response status
      if (response.statusCode == 200) {
        print("Order cancelled successfully");
      } else {
        throw Exception('Failed to cancel the order');
      }
    } catch (e) {
      // Handle error
      print('Error cancelling the order: $e');
    }
  }

}

