<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Bill;
use App\Models\Load;
use App\Services\FakeDigitalSignatureService;
use App\Services\RmtoService;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class BillController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        try {
            $perPage = $request->input('per_page', 15);
            $bills = Bill::with(['transportLoad', 'transportLoad.requester', 'transportLoad.driver'])
                ->when($request->input('load_id'), function ($query, $loadId) {
                    $query->where('load_id', $loadId);
                })
                ->when($request->input('status'), function ($query, $status) {
                    $query->where('status', $status);
                })
                ->when($request->input('bill_number'), function ($query, $billNumber) {
                    $query->where('bill_number', 'like', "%{$billNumber}%");
                })
                ->when($request->input('search'), function ($query, $search) {
                    $query->where(function ($q) use ($search) {
                        $q->where('bill_number', 'like', "%{$search}%")
                          ->orWhere('transport_license_plate', 'like', "%{$search}%")
                          ->orWhere('driver_license_number', 'like', "%{$search}%");
                    });
                })
                ->orderBy('created_at', 'desc')
                ->paginate($perPage);

            return response()->json([
                'success' => true,
                'message' => 'Bills retrieved successfully',
                'data' => $bills
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve bills',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'load_id' => 'required|exists:loads,id|unique:bills,load_id',
                'bill_number' => 'nullable|string|max:100|unique:bills,bill_number',
                'transport_license_plate' => 'required|string|max:50',
                'driver_license_number' => 'required|string|max:50',
                'issue_date' => 'required|date',
                'sender_info' => 'nullable|string',
                'receiver_info' => 'nullable|string',
                'cargo_details' => 'nullable|string',
                'declared_value' => 'required|numeric|min:0',
                'notes' => 'nullable|string',
                'status' => ['nullable', Rule::in(['pending', 'issued', 'confirmed', 'delivered', 'cancelled'])],
                'signature_image' => 'nullable|string',
                'delivery_confirmation_at' => 'nullable|date',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $billData = $validator->validated();

            // Set default status if not provided
            if (!isset($billData['status'])) {
                $billData['status'] = 'pending';
            }

            $signature = app(FakeDigitalSignatureService::class)->sign([
                'load_id' => $billData['load_id'],
                'bill_number' => $billData['bill_number'] ?? null,
                'declared_value' => $billData['declared_value'],
                'issue_date' => $billData['issue_date'],
            ]);

            if ($signature['success']) {
                $billData['digital_signature_provider'] = $signature['provider'];
                $billData['digital_signature'] = $signature['signature'];
            }

            // Bill number will be auto-generated in the model if not provided
            $bill = Bill::create($billData);
            $bill->load(['transportLoad', 'transportLoad.requester', 'transportLoad.driver']);

            $this->sendBillIssuedSms($bill);

            return response()->json([
                'success' => true,
                'message' => 'Bill created successfully',
                'data' => $bill
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create bill',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        try {
            $bill = Bill::with(['transportLoad', 'transportLoad.requester', 'transportLoad.driver'])->findOrFail($id);

            return response()->json([
                'success' => true,
                'message' => 'Bill retrieved successfully',
                'data' => $bill
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Bill not found',
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve bill',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        try {
            $bill = Bill::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'load_id' => ['sometimes', 'required', 'exists:loads,id', Rule::unique('bills')->ignore($id)],
                'bill_number' => ['nullable', 'string', 'max:100', Rule::unique('bills')->ignore($id)],
                'transport_license_plate' => 'sometimes|required|string|max:50',
                'driver_license_number' => 'sometimes|required|string|max:50',
                'issue_date' => 'sometimes|required|date',
                'sender_info' => 'nullable|string',
                'receiver_info' => 'nullable|string',
                'cargo_details' => 'nullable|string',
                'declared_value' => 'sometimes|required|numeric|min:0',
                'notes' => 'nullable|string',
                'status' => ['sometimes', 'required', Rule::in(['pending', 'issued', 'confirmed', 'delivered', 'cancelled'])],
                'signature_image' => 'nullable|string',
                'delivery_confirmation_at' => 'nullable|date',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $bill->update($validator->validated());
            $bill->load(['transportLoad', 'transportLoad.requester', 'transportLoad.driver']);

            return response()->json([
                'success' => true,
                'message' => 'Bill updated successfully',
                'data' => $bill->fresh(['transportLoad', 'transportLoad.requester', 'transportLoad.driver'])
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Bill not found',
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update bill',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            $bill = Bill::findOrFail($id);
            $bill->delete(); // Soft delete

            return response()->json([
                'success' => true,
                'message' => 'Bill deleted successfully',
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Bill not found',
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete bill',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function convertDispatchToBill(string $loadId)
    {
        try {
            $load = Load::with(['requester', 'driver'])->findOrFail($loadId);

            if (!$load->dispatch_issued_at) {
                return response()->json([
                    'success' => false,
                    'message' => 'Dispatch order has not been issued yet.',
                ], 422);
            }

            $bill = Bill::firstOrCreate(
                ['load_id' => $load->id],
                [
                    'transport_license_plate' => $load->fleet_plate_number,
                    'driver_license_number' => $load->driver_license_number,
                    'issue_date' => now(),
                    'sender_info' => sprintf('%s | %s | %s', $load->sender_name, $load->sender_national_code, $load->sender_phone),
                    'receiver_info' => sprintf('%s | %s | %s', $load->receiver_name, $load->receiver_national_code, $load->receiver_phone),
                    'cargo_details' => sprintf('%s | %s | %s', $load->cargo_type, $load->cargo_standard_code, $load->cargo_packaging),
                    'declared_value' => $load->cargo_value ?? $load->price,
                    'payment_terms' => $load->payment_terms,
                    'status' => 'issued',
                ]
            );

            if (empty($bill->digital_signature)) {
                $signature = app(FakeDigitalSignatureService::class)->sign([
                    'load_id' => $load->id,
                    'dispatch_order_number' => $load->dispatch_order_number,
                    'bill_number' => $bill->bill_number,
                ]);
                if ($signature['success']) {
                    $bill->digital_signature_provider = $signature['provider'];
                    $bill->digital_signature = $signature['signature'];
                    $bill->save();
                }
            }

            $bill->load(['transportLoad', 'transportLoad.requester', 'transportLoad.driver']);

            return response()->json([
                'success' => true,
                'message' => 'Dispatch order converted to internal bill successfully',
                'data' => $bill,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Load not found'], 404);
        }
    }

    public function cancel(string $id, Request $request)
    {
        try {
            $request->validate([
                'cancel_reason' => 'required|string|max:1000',
            ]);

            $bill = Bill::findOrFail($id);
            $bill->status = 'cancelled';
            $bill->cancel_reason = (string) $request->input('cancel_reason');
            $bill->cancelled_at = now();
            $bill->save();

            return response()->json([
                'success' => true,
                'message' => 'Bill cancelled successfully',
                'data' => $bill,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Bill not found'], 404);
        }
    }

    public function registerDelivery(string $id, Request $request)
    {
        try {
            $request->validate([
                'delivery_confirmation_at' => 'nullable|date',
            ]);

            $bill = Bill::findOrFail($id);
            $bill->status = 'delivered';
            $bill->delivery_confirmation_at = $request->input('delivery_confirmation_at', now());
            $bill->save();

            return response()->json([
                'success' => true,
                'message' => 'Delivery registered successfully',
                'data' => $bill,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Bill not found'], 404);
        }
    }

    public function registerDriverReceipt(string $id, Request $request)
    {
        try {
            $request->validate([
                'driver_receipt_notes' => 'nullable|string|max:2000',
            ]);

            $bill = Bill::findOrFail($id);
            $bill->driver_receipt_at = now();
            $bill->driver_receipt_notes = (string) $request->input('driver_receipt_notes', '');
            $bill->save();

            return response()->json([
                'success' => true,
                'message' => 'Driver receipt registered successfully',
                'data' => $bill,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Bill not found'], 404);
        }
    }

    public function setPaymentTerms(string $id, Request $request)
    {
        try {
            $request->validate([
                'payment_terms' => 'required|string|max:2000',
            ]);

            $bill = Bill::findOrFail($id);
            $bill->payment_terms = (string) $request->input('payment_terms');
            $bill->save();

            return response()->json([
                'success' => true,
                'message' => 'Payment terms saved successfully',
                'data' => $bill,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Bill not found'], 404);
        }
    }

    public function markReturned(string $id, Request $request)
    {
        try {
            $request->validate([
                'notes' => 'nullable|string|max:1000',
            ]);

            $bill = Bill::findOrFail($id);
            $bill->is_returned = true;
            $bill->returned_at = now();
            if ($request->filled('notes')) {
                $bill->notes = trim((string) ($bill->notes . PHP_EOL . 'RETURN: ' . $request->input('notes')));
            }
            $bill->save();

            return response()->json([
                'success' => true,
                'message' => 'Returned bill registered successfully',
                'data' => $bill,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json(['success' => false, 'message' => 'Bill not found'], 404);
        }
    }

    /**
     * Test RMTO bill of lading registration
     */
    public function testRMTOBillOfLading(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'bill_number' => 'required|integer',
                'serial' => 'required|string|max:10',
                'issue_date' => 'required|array',
                'issue_date.year' => 'required|integer|min:1400|max:1500',
                'issue_date.month' => 'required|integer|min:1|max:12',
                'issue_date.day' => 'required|integer|min:1|max:31',
                'issue_time' => 'required|string|regex:/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/',
                'lander_type_code' => 'required|integer',
                'origin_city_code' => 'required|integer',
                'destination_city_code' => 'required|integer',
                'sender' => 'required|array',
                'sender.name' => 'required|string',
                'sender.national_code' => 'required|string|size:10',
                'sender.postal_code' => 'required|string|size:10',
                'receiver' => 'required|array',
                'receiver.name' => 'required|string',
                'receiver.national_code' => 'required|string|size:10',
                'receiver.postal_code' => 'required|string|size:10',
                'freighter_card_number' => 'required|string',
                'first_driver_card_number' => 'required|string',
                'first_driver_national_id' => 'required|string|size:10',
                'cost' => 'required|integer|min:0',
                'total_cost' => 'required|numeric|min:0',
                'goods' => 'required|array|min:1',
                'goods.*.good_type_code' => 'required|integer',
                'goods.*.weight' => 'required|integer|min:1',
                'goods.*.value' => 'required|numeric|min:0',
                'requester_phone' => 'nullable|string|regex:/^09[0-9]{9}$/',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $validated = $validator->validated();

            // Prepare RMTO bill data
            $rmtoData = [
                'Number' => $validated['bill_number'],
                'IssueDate' => [
                    'Year' => $validated['issue_date']['year'],
                    'Month' => $validated['issue_date']['month'],
                    'Day' => $validated['issue_date']['day'],
                ],
                'IssueTime' => $validated['issue_time'],
                'LanderTypeCode' => $validated['lander_type_code'],
                'OriginCityCode' => $validated['origin_city_code'],
                'DestinationCityCode' => $validated['destination_city_code'],
                'Sender' => [
                    'Name' => $validated['sender']['name'],
                    'NationalCode' => $validated['sender']['national_code'],
                    'PostalCode' => $validated['sender']['postal_code'],
                ],
                'Receiver' => [
                    'Name' => $validated['receiver']['name'],
                    'NationalCode' => $validated['receiver']['national_code'],
                    'PostalCode' => $validated['receiver']['postal_code'],
                ],
                'FreighterCardNumber' => $validated['freighter_card_number'],
                'FirstDriverCardNumber' => $validated['first_driver_card_number'],
                'FirstDriverNationalId' => $validated['first_driver_national_id'],
                'Serial' => $validated['serial'],
                'Cost' => $validated['cost'],
                'TotalCost' => $validated['total_cost'],
                'CompanyCommission' => $validated['company_commission'] ?? 0,
                'SenderAddress' => $validated['sender']['address'] ?? '',
                'ReceiverAddress' => $validated['receiver']['address'] ?? '',
                'ClientCode' => config('rmto.client_code'),
                'ClientVersion' => config('rmto.client_version'),
            ];

            // Add goods list
            $rmtoData['GoodInfoList'] = array_map(function ($good) {
                return [
                    'GoodTypeCode' => $good['good_type_code'],
                    'Weight' => $good['weight'],
                    'Value' => $good['value'],
                    'HSCode' => $good['hs_code'] ?? 0,
                    'PackingTypeCode' => $good['packing_type_code'] ?? 1,
                ];
            }, $validated['goods']);

            // Call RMTO service
            $rmtoService = new RmtoService();
            $result = $rmtoService->insertBillOfLading($rmtoData);

            if ($result) {
                if (!empty($validated['requester_phone'])) {
                    $this->sendBillWillBeIssuedSms(
                        (string) $validated['requester_phone'],
                        (string) ($validated['bill_number'] ?? ''),
                    );
                }

                return response()->json([
                    'success' => true,
                    'message' => 'Bill of lading registered successfully with RMTO',
                    'data' => $result,
                    'trace_code' => $result['TraceCode'] ?? $result['trace_code'] ?? null,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to register bill of lading with RMTO',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to test RMTO bill of lading',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    private function sendBillIssuedSms(Bill $bill): void
    {
        try {
            $smsService = app(SmsService::class);
            $requesterPhone = (string) ($bill->transportLoad?->requester?->phone ?? '');
            $driverPhone = (string) ($bill->transportLoad?->driver?->phone ?? '');
            $driverName = (string) ($bill->transportLoad?->driver?->name ?? 'راننده');
            $billCode = (string) ($bill->bill_number ?? $bill->id);
            $supportPhone = (string) config('sms.support_phone', '');
            $downloadLink = url('/api/bills/' . $bill->id);

            if ($requesterPhone !== '') {
                $smsService->sendIssuanceBillLandingFromSite(
                    $requesterPhone,
                    $billCode,
                    $downloadLink,
                    $supportPhone
                );
            }

            if ($driverPhone !== '') {
                $smsService->sendDriverReceiveWaybill(
                    $driverPhone,
                    $billCode,
                    $driverName
                );
            }
        } catch (\Throwable $exception) {
            Log::warning('Failed to send bill issued sms', [
                'bill_id' => $bill->id,
                'error' => $exception->getMessage(),
            ]);
        }
    }

    private function sendBillWillBeIssuedSms(string $receptor, string $trackingCode): void
    {
        try {
            $smsService = app(SmsService::class);
            $smsService->sendIssuanceBillLandingFromBita24(
                $receptor,
                $trackingCode,
                (string) config('sms.support_phone', '')
            );
        } catch (\Throwable $exception) {
            Log::warning('Failed to send will be issued sms', [
                'error' => $exception->getMessage(),
            ]);
        }
    }

    /**
     * Get driver info from RMTO
     */
    public function getDriverInfo(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'type' => 'required|in:card,national_id',
                'value' => 'required|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $rmtoService = new RmtoService();
            
            if ($request->type === 'card') {
                $result = $rmtoService->getDriverBySmartCardNo($request->value);
            } else {
                $result = $rmtoService->getDriverByNationalId($request->value);
            }

            if ($result) {
                return response()->json([
                    'success' => true,
                    'message' => 'Driver info retrieved successfully',
                    'data' => $result,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to retrieve driver info',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get driver info',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get freighter (vehicle) info from RMTO
     */
    public function getFreighterInfo(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'card_number' => 'required|string',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $rmtoService = new RmtoService();
            $result = $rmtoService->getFreighterBySmartCardNo($request->card_number);

            if ($result) {
                return response()->json([
                    'success' => true,
                    'message' => 'Freighter info retrieved successfully',
                    'data' => $result,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to retrieve freighter info',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get freighter info',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Send OTP for bill of lading
     */
    public function sendOTP(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'mobile' => 'required|string|regex:/^09[0-9]{9}$/',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $rmtoService = new RmtoService();
            $result = $rmtoService->sendOTP($request->mobile);

            if ($result) {
                return response()->json([
                    'success' => true,
                    'message' => 'OTP sent successfully',
                    'data' => $result,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to send OTP',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to send OTP',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get RMTO current date/time
     */
    public function getRMTOCurrentDate()
    {
        try {
            $rmtoService = new RmtoService();
            $date = $rmtoService->getCurrentDate();

            if ($date) {
                return response()->json([
                    'success' => true,
                    'message' => 'RMTO current date retrieved successfully',
                    'date' => $date,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to get RMTO current date',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to get RMTO current date',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get RMTO current date/time (RAW SOAP)
     */
    public function getRMTOCurrentDateRaw()
    {
        try {
            $rmtoService = new RmtoService();
            $date = $rmtoService->getCurrentDate();

            if ($date) {
                return response()->json([
                    'success' => true,
                    'message' => 'Raw RMTO SOAP response',
                    'date' => $date,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to get RMTO current date',
                ], 400);
            }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Exception',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Inquiry real person (national code)
     */
    public function inquiryRealPerson(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'national_code' => 'required|string|size:10',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $rmtoService = new RmtoService();
            $result = $rmtoService->inquiryLegalPerson($request->national_code);

            if ($result) {
                return response()->json([
                    'success' => true,
                    'message' => 'Inquiry completed successfully',
                    'data' => $result,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Inquiry failed',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to inquiry',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Inquiry postal code
     */
    public function inquiryPostalCode(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'postal_code' => 'required|string|size:10',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $rmtoService = new RmtoService();
            $result = $rmtoService->inquiryPostalCode($request->postal_code);

            if ($result) {
                return response()->json([
                    'success' => true,
                    'message' => 'Inquiry completed successfully',
                    'data' => $result,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Inquiry failed',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to inquiry',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Inquiry freight price between provinces
     */
    public function inquiryPrice(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'origin_code' => 'required|integer',
                'dest_code' => 'required|integer',
                'bargir_code' => 'required|integer',
                'kala_code' => 'required|integer',
                'weight' => 'required|numeric|min:0',
                'company_commission' => 'nullable|numeric|min:0',
                'is_traffic_load' => 'nullable|boolean',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $rmtoService = new RmtoService();
            $result = $rmtoService->inquiryOrfOstanPrice($request->all());

            if ($result) {
                return response()->json([
                    'success' => true,
                    'message' => 'Price inquiry completed successfully',
                    'data' => $result,
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Price inquiry failed',
                ], 400);
            }

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to inquiry price',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
