@props(['salesOrder'])
@php
    $belongsToSalesOrder = function ($document) use ($salesOrder) {
        $current = $document;
        while ($current->parent) {
            $current = $current->parent;
            if ($current->id === $salesOrder->id) return true;
        }
        return ($document->details['sales_order_reference'] ?? null) === $salesOrder->reference_number;
    };
    $invoices = \App\Models\OperationalDocument::where('business_id', $salesOrder->business_id)->where('type', 'invoices')->get()
        ->filter($belongsToSalesOrder)->values();
    $invoiceIds = $invoices->pluck('id');
    $verifiedByInvoice = \Illuminate\Support\Facades\DB::table('payment_allocations')
        ->join('payments', 'payments.id', '=', 'payment_allocations.payment_id')
        ->whereIn('payment_allocations.invoice_id', $invoiceIds)->where('payments.status', 'verified')
        ->selectRaw('payment_allocations.invoice_id, SUM(payment_allocations.amount) as paid')->groupBy('payment_allocations.invoice_id')->pluck('paid', 'invoice_id');
    $paymentHistory = \Illuminate\Support\Facades\DB::table('payment_allocations')
        ->join('payments', 'payments.id', '=', 'payment_allocations.payment_id')
        ->leftJoin('receipts', 'receipts.payment_id', '=', 'payments.id')
        ->join('operational_documents as invoices', 'invoices.id', '=', 'payment_allocations.invoice_id')
        ->whereIn('payment_allocations.invoice_id', $invoiceIds)->where('payments.status', 'verified')
        ->select('payments.id', 'payments.reference', 'payments.payer', 'payments.received_at', 'payments.status', 'payment_allocations.amount as allocated_amount', 'invoices.reference_number as invoice_reference', 'receipts.receipt_number')
        ->orderByDesc('payments.verified_at')->get();
    $tradePayments = \Illuminate\Support\Facades\DB::table('trade_document_payments')
        ->join('operational_documents as invoices', 'invoices.trade_document_id', '=', 'trade_document_payments.trade_document_id')
        ->whereIn('invoices.id', $invoiceIds)->where('trade_document_payments.status', 'posted')
        ->select('trade_document_payments.reference', 'trade_document_payments.amount', 'trade_document_payments.payment_type', 'trade_document_payments.paid_at', 'trade_document_payments.payer_name', 'trade_document_payments.receipt_number', 'invoices.reference_number as invoice_reference')
        ->orderByDesc('trade_document_payments.paid_at')->get();
    $commercial = $salesOrder->details ?? [];
    $audits = $salesOrder->histories()->where('action', 'sales_order_payment_status_updated')->latest()->limit(5)->get();
@endphp
<div class="border rounded p-2 mt-2 bg-light">
    <div class="d-flex justify-content-between align-items-center"><strong class="small">Commercial payment status</strong><span class="badge bg-{{ ($commercial['payment_status'] ?? 'unpaid') === 'paid' ? 'success' : (($commercial['payment_status'] ?? 'unpaid') === 'partially_paid' ? 'warning text-dark' : 'secondary') }}">{{ ucwords(str_replace('_', ' ', $commercial['payment_status'] ?? 'unpaid')) }}</span></div>
    <div class="row small mt-2"><div class="col">Invoices: <strong>{{ $invoices->count() }}</strong></div><div class="col">Paid: <strong>{{ number_format((float) ($commercial['amount_paid'] ?? 0), 2) }}</strong></div><div class="col">Outstanding: <strong>{{ number_format((float) ($commercial['balance_due'] ?? 0), 2) }}</strong></div></div>
    @if($invoices->isNotEmpty())
        <details class="mt-2"><summary class="small">Linked invoices, allocations &amp; payment history</summary>
            <div class="table-responsive mt-1"><table class="table table-sm mb-1 small"><thead><tr><th>Invoice</th><th>Status</th><th>Total</th><th>Verified</th><th>Balance</th></tr></thead><tbody>
            @foreach($invoices as $invoice) @php($total = (float) ($invoice->details['total_amount'] ?? $invoice->details['grand_total'] ?? 0)) @php($paid = (float) ($verifiedByInvoice[$invoice->id] ?? $invoice->details['amount_paid'] ?? 0))
                <tr><td>{{ $invoice->reference_number }}</td><td>{{ ucwords(str_replace('_', ' ', $invoice->status)) }}</td><td>{{ number_format($total, 2) }}</td><td>{{ number_format($paid, 2) }}</td><td>{{ number_format(max(0, $total - $paid), 2) }}</td></tr>
            @endforeach
            </tbody></table></div>
            @forelse($paymentHistory as $payment)<div class="small">{{ $payment->received_at }} · {{ $payment->reference }} · {{ $payment->invoice_reference }} · {{ number_format((float) $payment->allocated_amount, 2) }} · {{ $payment->payer }} @if($payment->receipt_number)· Receipt {{ $payment->receipt_number }}@endif</div>@empty<div class="small text-muted">No verified native payment allocations yet.</div>@endforelse
            @foreach($tradePayments as $payment)<div class="small">{{ $payment->paid_at }} — {{ strtoupper($payment->payment_type) }} — {{ $payment->reference }} — {{ $payment->invoice_reference }} — {{ number_format((float) $payment->amount, 2) }} @if($payment->receipt_number)— Receipt {{ $payment->receipt_number }}@endif</div>@endforeach
        </details>
    @endif
    @if($audits->isNotEmpty())<details class="mt-2"><summary class="small">Payment audit</summary>@foreach($audits as $audit)<div class="small">{{ $audit->created_at }} · {{ $audit->comment }}</div>@endforeach</details>@endif
</div>
