@php
    $courierSettingsService = app(\App\Services\Courier\CourierSettingsService::class);
    $integration = $courierSettingsService->getIntegrationSettings();
    $shipment = $order->courierShipment;
    $courierEnabled = $courierSettingsService->isIntegrationEnabled();
    $allowedStatuses = data_get($integration, 'allowed_booking_statuses', ['confirmed', 'accepted', 'processing']);
    $canSendToCourier = $order->order_type !== 'parcel'
        && $courierEnabled
        && in_array($order->order_status, $allowedStatuses, true)
        && (! $shipment || ! $shipment->hasSuccessfulBooking())
        && ! $order->delivery_man_id;
    $canSyncCourier = $order->order_type !== 'parcel'
        && $courierEnabled
        && data_get($integration, 'manual_sync_enabled', true)
        && $shipment?->hasSuccessfulBooking();
    $statusLabel = match ($shipment?->booking_status) {
        'booked' => 'Booked',
        'failed' => 'Failed',
        'not_sent' => 'Not Sent',
        default => 'Not Sent',
    };
    $formatNullableCurrency = static fn ($amount) => $amount === null
        ? translate('N/A')
        : \App\CentralLogics\Helpers::format_currency($amount);
    $courierEventDate = null;
    $settlementReference = null;
    $codSettlementLabel = translate('N/A');
    $codSettlementClass = 'badge-soft-secondary';
    $collectedAmountLabel = translate('Not Settled');
    $orderHasUnpaidBalance = false;

    if ($shipment) {
        $responsePayload = $shipment->response_payload ?? [];
        $courierEventDate = collect([
            $shipment->settlement_paid_at?->format('d M Y h:i A'),
            $shipment->cod_collected_at?->format('d M Y h:i A'),
            data_get($responsePayload, 'payment_date'),
            data_get($responsePayload, 'collection_date'),
            data_get($responsePayload, 'settlement_date'),
            data_get($responsePayload, 'paid_at'),
            data_get($responsePayload, 'updated_at'),
        ])->first(fn ($value) => filled($value));
        $settlementReference = collect([
            $shipment->settlement_reference,
            data_get($responsePayload, 'settlement_reference'),
            data_get($responsePayload, 'payment_reference'),
            data_get($responsePayload, 'transaction_id'),
            data_get($responsePayload, 'trx_id'),
        ])->first(fn ($value) => filled($value));
        $orderHasUnpaidBalance = $order->payment_status === 'unpaid'
            || ($order->payment_status === 'partially_paid'
                && ($order->relationLoaded('payments')
                    ? $order->payments->contains('payment_status', 'unpaid')
                    : $order->payments()->where('payment_status', 'unpaid')->exists()));

        if ((float) $shipment->collectable_amount <= 0) {
            $codSettlementLabel = translate('No COD');
            $codSettlementClass = 'badge-soft-secondary';
        } elseif ($shipment->courier_accounting_synced_at || $shipment->isCodReceived()) {
            $codSettlementLabel = translate('Received / Accounted');
            $codSettlementClass = 'badge-soft-success';
            $collectedAmountLabel = \App\CentralLogics\Helpers::format_currency($shipment->cod_collected_amount ?? $shipment->collectable_amount);
        } elseif ($shipment->cod_collection_status === 'collected') {
            $codSettlementLabel = translate('Collected - Settlement Pending');
            $codSettlementClass = 'badge-soft-warning';
            $collectedAmountLabel = \App\CentralLogics\Helpers::format_currency($shipment->cod_collected_amount ?? $shipment->collectable_amount);
        } elseif ($order->order_status === 'delivered') {
            $codSettlementLabel = translate('Delivered - Settlement Pending');
            $codSettlementClass = 'badge-soft-warning';
        } else {
            $codSettlementLabel = translate('Pending');
            $codSettlementClass = 'badge-soft-info';
        }
    }

    $codAccountingMismatch = $shipment
        && (float) $shipment->collectable_amount > 0
        && $order->order_status === 'delivered'
        && ! $shipment->courier_accounting_synced_at
        && $orderHasUnpaidBalance;
@endphp

@if ($order->order_type !== 'parcel')
    <div class="card mt-2">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-start flex-wrap __gap-12px">
                <div>
                    <h5 class="card-title text-dark mb-1">
                        <span class="card-header-icon">
                            <i class="tio-local-shipping"></i>
                        </span>
                        <span>{{ translate('Courier Automation') }}</span>
                    </h5>
                    <p class="fs-12 text-muted mb-0">{{ translate('Manual review first, then one-click courier booking.') }}</p>
                </div>
                <div class="d-flex flex-wrap __gap-8px">
                    @if ($canSendToCourier)
                        <form action="{{ route('admin.order.courier.send', $order) }}" method="post">
                            @csrf
                            <button type="submit" class="btn btn--primary btn-sm">{{ $shipment && $shipment->booking_status === 'failed' ? translate('Retry Send to Courier') : translate('Send to Courier') }}</button>
                        </form>
                    @endif
                    @if ($canSyncCourier)
                        <form action="{{ route('admin.order.courier.sync', $order) }}" method="post">
                            @csrf
                            <button type="submit" class="btn btn-outline-primary btn-sm">{{ translate('Sync Courier Status') }}</button>
                        </form>
                    @endif
                    @if ($shipment)
                        <a href="{{ route('admin.courier.ledger', ['invoice_no' => $order->id]) }}" class="btn btn-outline-primary btn-sm">
                            {{ translate('Ledger Entries') }}
                        </a>
                        @if (($shipment->settlement_status !== 'settled') && ($shipment->courier_id || $shipment->provider))
                            <a href="{{ route('admin.courier.settlements.create', ['courier_id' => $shipment->courier_id, 'invoice_no' => $order->id]) }}" class="btn btn-outline-success btn-sm">
                                {{ translate('Settle Courier COD') }}
                            </a>
                        @endif
                    @endif
                    @if (! $courierEnabled)
                        <a href="{{ route('admin.business-settings.third-party.courier.index') }}" class="btn btn-outline-secondary btn-sm">{{ translate('Configure Courier') }}</a>
                    @endif
                </div>
            </div>

            @if (! $courierEnabled)
                <div class="alert alert-soft-warning mt-3 mb-0">
                    {{ translate('Courier integration is disabled. Enable it from settings before sending any order to courier.') }}
                </div>
            @elseif ($order->delivery_man_id && ! $shipment?->hasSuccessfulBooking())
                <div class="alert alert-soft-warning mt-3 mb-0">
                    {{ translate('This order already has a delivery man assigned. Remove manual assignment before sending to courier.') }}
                </div>
            @elseif (! $shipment && ! in_array($order->order_status, $allowedStatuses, true))
                <div class="alert alert-soft-info mt-3 mb-0">
                    {{ translate('Send to Courier button becomes available only after manual confirmation or packaging.') }}
                </div>
            @endif

            <div class="row g-3 mt-3">
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Provider') }}</div>
                        <div class="font-weight-semibold">{{ ucfirst($shipment?->provider ?? data_get($integration, 'default_provider', 'steadfast')) }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Booking Status') }}</div>
                        <div class="font-weight-semibold">{{ translate($statusLabel) }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Collectable Amount') }}</div>
                        @php
                            if ($shipment) {
                                $collectableDisplay = \App\CentralLogics\Helpers::format_currency($shipment->collectable_amount ?? 0);
                                $collectableNote = null;
                            } else {
                                try {
                                    $previewAmount = app(\App\Services\Courier\CourierPayloadBuilder::class)->resolveCollectableAmount($order);
                                    $collectableDisplay = \App\CentralLogics\Helpers::format_currency($previewAmount);
                                    $collectableNote = translate('Expected on booking');
                                } catch (\Throwable $e) {
                                    $collectableDisplay = translate('N/A');
                                    $collectableNote = null;
                                }
                            }
                        @endphp
                        <div class="font-weight-semibold">{{ $collectableDisplay }}</div>
                        @if (!empty($collectableNote))
                            <div class="text-muted fs-11">{{ $collectableNote }}</div>
                        @endif
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('COD Settlement Status') }}</div>
                        <div><span class="badge {{ $codSettlementClass }}">{{ $codSettlementLabel }}</span></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Collected Amount') }}</div>
                        <div class="font-weight-semibold">{{ $collectedAmountLabel }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Parcel ID') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_parcel_id ?? translate('Not Sent') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Consignment ID') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_consignment_id ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Tracking ID') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_tracking_id ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Courier Status') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_status ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Courier Status Code') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_status_code ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Courier Status Text') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_status_text ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Rider ID') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_rider_id ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Rider Name') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_rider_name ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Rider Mobile') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_rider_phone ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Out for Delivery Confirmed At') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->out_for_delivery_at?->format('d M Y h:i A') ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Courier Event Reference') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->courier_event_reference ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Actual Delivery Charge') }}</div>
                        <div class="font-weight-semibold">{{ $formatNullableCurrency($shipment?->actual_delivery_cost) }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Actual Return Charge') }}</div>
                        <div class="font-weight-semibold">{{ $formatNullableCurrency($shipment?->actual_return_cost) }}</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Actual COD Charge') }}</div>
                        <div class="font-weight-semibold">{{ $formatNullableCurrency($shipment?->actual_cod_charge) }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Sent Time') }}</div>
                        <div class="font-weight-semibold">{{ $shipment?->sent_to_courier_at ? $shipment->sent_to_courier_at->format('d M Y h:i A') : translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Last Sync Time') }}</div>
                        <div class="font-weight-semibold">{{ $shipment?->courier_synced_at ? $shipment->courier_synced_at->format('d M Y h:i A') : translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('COD Collected Time') }}</div>
                        <div class="font-weight-semibold">{{ $shipment?->cod_collected_at ? $shipment->cod_collected_at->format('d M Y h:i A') : translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Settlement Paid Time') }}</div>
                        <div class="font-weight-semibold">{{ $shipment?->settlement_paid_at ? $shipment->settlement_paid_at->format('d M Y h:i A') : translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Accounting Synced Time') }}</div>
                        <div class="font-weight-semibold">{{ $shipment?->courier_accounting_synced_at ? $shipment->courier_accounting_synced_at->format('d M Y h:i A') : translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('COD Received By') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->codReceivedBy?->full_name ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Courier Event Date') }}</div>
                        <div class="font-weight-semibold text-break">{{ $courierEventDate ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Settlement Reference') }}</div>
                        <div class="font-weight-semibold text-break">{{ $settlementReference ?? translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Settlement Status') }}</div>
                        <div class="font-weight-semibold text-break">{{ $shipment?->settlement_status ? translate(str_replace('_', ' ', $shipment->settlement_status)) : translate('N/A') }}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="bg-light2 rounded p-3 h-100">
                        <div class="text-muted fs-12 mb-1">{{ translate('Settled Amount') }}</div>
                        <div class="font-weight-semibold">{{ $formatNullableCurrency($shipment?->settled_amount) }}</div>
                    </div>
                </div>
            </div>

            @if ($codAccountingMismatch)
                <div class="alert alert-soft-danger mt-3 mb-0">
                    <strong>{{ translate('COD Accounting Alert') }}:</strong>
                    {{ translate('Courier delivered this COD order, but COD is not marked received and the order still has unpaid balance. Check courier settlement before closing accounting.') }}
                </div>
            @endif

            @if ($shipment?->courier_accounting_note)
                <div class="alert alert-soft-info mt-3 mb-0 text-break">
                    <strong>{{ translate('Courier Accounting Note') }}:</strong> {{ $shipment->courier_accounting_note }}
                </div>
            @endif

            @if ($shipment?->last_error_message)
                <div class="alert alert-soft-danger mt-3 mb-0 text-break">
                    <strong>{{ translate('Last Courier Error') }}:</strong> {{ $shipment->last_error_message }}
                </div>
            @endif

            @if ($shipment?->parcel_note)
                <div class="bg-light2 rounded p-3 mt-3">
                    <div class="text-muted fs-12 mb-1">{{ translate('Parcel Note') }}</div>
                    <div class="font-weight-medium text-break">{{ $shipment->parcel_note }}</div>
                </div>
            @endif

            @if ($shipment && $shipment->logs->count() > 0)
                <div class="mt-3">
                    <h6 class="mb-2">{{ translate('Courier Logs') }}</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-borderless mb-0">
                            <thead>
                                <tr>
                                    <th>{{ translate('Action') }}</th>
                                    <th>{{ translate('Result') }}</th>
                                    <th>{{ translate('HTTP') }}</th>
                                    <th>{{ translate('Time') }}</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($shipment->logs->take(5) as $log)
                                    <tr>
                                        <td class="text-capitalize">{{ $log->action }}</td>
                                        <td class="text-break">{{ $log->success ? translate('Success') : ($log->error_message ?? translate('Failed')) }}</td>
                                        <td>{{ $log->http_status ?? '-' }}</td>
                                        <td>{{ $log->created_at?->format('d M Y h:i A') }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            @endif
        </div>
    </div>
@endif
