@props(['account'])
@php
    $documents = \App\Models\OperationalDocument::where('business_id', $account->business_id)
        ->where('account_id', $account->id)->latest()->get()->groupBy('type');
    $labels = ['sales-orders' => 'Sales Orders', 'contracts' => 'Contracts', 'handovers' => 'Handovers', 'deliveries' => 'Deliveries', 'invoices' => 'Invoices'];
    $invoices = $documents->get('invoices', collect());
    $financialInvoices = $invoices->whereIn('status', ['approved', 'sent', 'partially_paid', 'paid', 'closed']);
    $invoiceIds = $financialInvoices->pluck('id');
    $invoiceTotal = $financialInvoices->sum(fn ($invoice) => (float) ($invoice->details['total_amount'] ?? 0));
    $verifiedAllocations = $invoiceIds->isEmpty() ? 0 : (float) \Illuminate\Support\Facades\DB::table('payment_allocations')
        ->join('payments', 'payments.id', '=', 'payment_allocations.payment_id')
        ->whereIn('payment_allocations.invoice_id', $invoiceIds)
        ->where('payments.business_id', $account->business_id)
        ->where('payments.status', 'verified')->sum('payment_allocations.amount');
    $accountBalance = max(0, $invoiceTotal - $verifiedAllocations);
    $overdue = $invoices->filter(fn ($invoice) => in_array($invoice->status, ['sent', 'partially_paid'], true)
        && ! empty($invoice->details['due_date']) && \Carbon\Carbon::parse($invoice->details['due_date'])->isPast())->count();
    $payments = \Illuminate\Support\Facades\DB::table('payments')
        ->where('business_id', $account->business_id)->where('account_id', $account->id)->latest('id')->get();
    $receipts = \Illuminate\Support\Facades\DB::table('receipts')
        ->join('payments', 'payments.id', '=', 'receipts.payment_id')
        ->where('receipts.business_id', $account->business_id)->where('payments.account_id', $account->id)
        ->where('payments.status', 'verified')
        ->select('receipts.*', 'payments.id as payment_record_id', 'payments.reference as payment_reference', 'payments.amount', 'payments.received_at', 'payments.payer', 'payments.status as payment_status', 'payments.attachment_path')
        ->latest('receipts.id')->get();
@endphp

<div class="card mb-3">
    <div class="card-header"><h5 class="mb-0">Commercial &amp; delivery history</h5></div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-4"><div class="border rounded p-3"><small class="text-muted">Account balance</small><strong class="d-block fs-4">{{ number_format($accountBalance, 2) }}</strong><small class="text-muted">Invoices less verified allocations</small></div></div>
            <div class="col-md-4"><div class="border rounded p-3"><small class="text-muted">Verified collections</small><strong class="d-block fs-4">{{ number_format($verifiedAllocations, 2) }}</strong></div></div>
            <div class="col-md-4"><div class="border rounded p-3"><small class="text-muted">Overdue invoices</small><strong class="d-block fs-4">{{ $overdue }}</strong></div></div>
        </div>

        @foreach ($labels as $type => $label)
            <h6 class="mt-3">{{ $label }}</h6>
            <div class="table-responsive"><table class="table table-sm"><thead><tr><th>Reference</th><th>Status</th><th>Amount</th><th>Date</th><th></th></tr></thead><tbody>
                @forelse ($documents->get($type, collect())->take(10) as $document)
                    <tr><td>{{ $document->reference_number }}</td><td>{{ ucwords(str_replace('_', ' ', $document->status)) }}</td><td>{{ number_format((float) ($document->details['total_amount'] ?? $document->details['grand_total'] ?? $document->details['contract_value'] ?? 0), 2) }}</td><td>{{ $document->details['invoice_date'] ?? $document->details['order_date'] ?? $document->details['contract_date'] ?? $document->details['planned_delivery_date'] ?? $document->created_at->toDateString() }}</td><td><a class="btn btn-sm btn-outline-primary" href="{{ route('operational-documents.index', [$type, 'record' => $document->id]) }}">Open</a></td></tr>
                @empty <tr><td colspan="5" class="text-muted">No linked records.</td></tr>
                @endforelse
            </tbody></table></div>
        @endforeach

        <h6 class="mt-3">Payments</h6>
        <div class="table-responsive"><table class="table table-sm"><thead><tr><th>Reference</th><th>Amount</th><th>Date</th><th>Payer</th><th>Status</th><th>Attachment</th><th></th></tr></thead><tbody>
            @forelse ($payments->take(10) as $payment)
                <tr><td>{{ $payment->reference }}</td><td>{{ number_format((float) $payment->amount, 2) }}</td><td>{{ $payment->received_at }}</td><td>{{ $payment->payer }}</td><td>{{ ucwords($payment->status) }}</td><td>@if ($payment->attachment_path)<a href="{{ asset('storage/'.$payment->attachment_path) }}" target="_blank" rel="noopener">Open attachment</a>@else <span class="text-muted">None</span>@endif</td><td><a class="btn btn-sm btn-outline-primary" href="{{ route('payments.index') }}#payment-{{ $payment->id }}">Open</a></td></tr>
            @empty <tr><td colspan="7" class="text-muted">No linked payments.</td></tr>
            @endforelse
        </tbody></table></div>

        <h6 class="mt-3">Receipts</h6>
        <div class="table-responsive"><table class="table table-sm"><thead><tr><th>Receipt reference</th><th>Amount</th><th>Date</th><th>Payer</th><th>Status</th><th>Attachment</th><th></th></tr></thead><tbody>
            @forelse ($receipts->take(10) as $receipt)
                <tr><td>{{ $receipt->receipt_number }}</td><td>{{ number_format((float) $receipt->amount, 2) }}</td><td>{{ $receipt->issued_at }}</td><td>{{ $receipt->payer }}</td><td>{{ ucwords($receipt->payment_status) }}</td><td>@if ($receipt->attachment_path)<a href="{{ asset('storage/'.$receipt->attachment_path) }}" target="_blank" rel="noopener">Open attachment</a>@else <span class="text-muted">None</span>@endif</td><td><a class="btn btn-sm btn-outline-primary" href="{{ route('payments.index') }}#payment-{{ $receipt->payment_record_id }}">Open payment {{ $receipt->payment_reference }}</a></td></tr>
            @empty <tr><td colspan="7" class="text-muted">No verified receipts.</td></tr>
            @endforelse
        </tbody></table></div>
    </div>
</div>
