@extends('layouts.app') @section('title', 'Invoice | ' . ($invoice->invoice_number ?? '')) @section('styles') @endsection @section('content') @php $hs = \App\Helpers\HospitalSettings::all(); $patient = $invoice->patient; $visit = $invoice->visit; // ── Resolve all payers for this invoice ────────────────────────────── // An invoice may be split across multiple insurers (e.g. GA + SHA) and // may also have cash/M-Pesa payments on top. We need to list every // distinct payer with the correct amount, and show any unpaid balance // as the patient's responsibility. $allPayments = $invoice->payments ?? collect(); // Insurance payments: group by insurer name so multiple entries from the // same insurer roll up into a single row. $insurancePayers = $allPayments ->where('payment_method', 'insurance') ->groupBy(function ($p) { return $p->description ?? $p->insuranceCompany?->name ?? $p->insurance_provider ?? 'Insurance'; }) ->map(fn($grp, $name) => [ 'name' => $name, 'amount' => $grp->sum('amount'), ]) ->values(); // Non-insurance payments (cash, mpesa, card, bank transfer) — grouped // by method label. $otherPayers = $allPayments ->whereNotIn('payment_method', ['insurance']) ->groupBy('payment_method') ->map(fn($grp, $method) => [ 'name' => ucfirst(str_replace('_', ' ', $method)), 'amount' => $grp->sum('amount'), ]) ->values(); // Overall flags for the header $hasInsurance = $insurancePayers->isNotEmpty(); $isInsurance = $hasInsurance; // header uses this to label "INSURANCE INVOICE" // Build a primary insurer name for the INSURANCE INFORMATION panel at // the top (we still show the panel if any insurer exists; if multiple, // we name them all joined by " + "). $insurerName = $hasInsurance ? $insurancePayers->pluck('name')->implode(' + ') : null; // Fallback for invoices that have NO payments recorded yet: // use the invoice's declared payment_mode/insurer so we still show // a sensible "PLEASE PAY" row. $paymentMode = $invoice->payment_mode ?? $visit?->payment_mode ?? 'cash'; if (!$hasInsurance && $otherPayers->isEmpty()) { if (strtolower($paymentMode) === 'insurance') { $fallbackInsurer = $invoice->insuranceCompany?->name ?? $visit?->insuranceCompany?->name ?? 'Insurance'; $insurerName = $fallbackInsurer; $isInsurance = true; $hasInsurance = true; } } // Authorization code $authCode = $visit?->authorization_code ?? null; // ── SHA member identity for the INSURANCE INFORMATION panel ───── // SHA receipts/claims need the principal's SHA Number, Member Name // and Relationship printed alongside the insurer name. Two sources, // in priority order: // (1) the most-recent SHA-tagged payment on this invoice — what // was actually captured at point of payment and what the // receipt is going to print; // (2) the patient's stored SHA cover on file — for invoices that // are SHA but haven't received a payment yet. // We also surface the per-payment Auth Reference here (separate from // the visit's $authCode, which is the registration-time field — they // may differ when SHA issues a new auth per episode). $shaCompanyHdr = \App\Models\InsuranceCompany::where('code', 'SHA')->first(); $invoiceIsSha = $shaCompanyHdr && ($invoice->payment_mode ?? null) === 'insurance' && (int) ($invoice->insurance_company_id ?? 0) === (int) $shaCompanyHdr->id; $shaPay = $shaCompanyHdr ? $allPayments->whereNotNull('sha_number')->sortByDesc('created_at')->first() : null; $shaCover = (!$shaPay && $invoiceIsSha && $shaCompanyHdr) ? \App\Models\PatientInsurance::where('patient_id', $invoice->patient_id) ->where('insurance_company_id', $shaCompanyHdr->id) ->where('is_active', true) ->latest()->first() : null; $shaNumber = $shaPay->sha_number ?? $shaCover->member_number ?? null; $shaMemberName = $shaPay->sha_member_name ?? $shaCover->principal_name ?? null; $shaRelationship = $shaPay->sha_relationship ?? $shaCover->relationship ?? null; $shaAuthRef = $shaPay->sha_auth_reference ?? null; // Financial summary $subtotal = $invoice->subtotal ?? $invoice->total_amount; $discount = $invoice->discount_amount ?? 0; $waiver = $invoice->waiver_amount ?? 0; $grandTotal = $invoice->total_amount ?? 0; $amountPaid = (float) ($invoice->amount_paid ?? $allPayments->sum('amount')); $balanceDue = max(0, $grandTotal - ($insurancePayers->sum('amount') + $otherPayers->sum('amount'))); // Address split $addr = $hs['hospital_address'] ?? 'Utawala | 83 Park Estate, Kiguathi Rd'; if (str_contains($addr, '(')) { $addrLine1 = trim(substr($addr, 0, strpos($addr, '('))); $addrLine2 = trim(substr($addr, strpos($addr, '('))); } else { $addrLine1 = $addr; $addrLine2 = ''; } @endphp
Back Download PDF
{{-- ── LETTERHEAD ── --}}
Logo

{{ $hs['hospital_name'] ?? 'Clara Rosa Hospital Utawala' }}

{{ $addrLine1 }}

@if($addrLine2)

{{ $addrLine2 }}

@endif

Tel: {{ $hs['hospital_phone'] ?? '' }}

{{ $isInsurance ? 'INSURANCE INVOICE' : 'INVOICE' }}

No: {{ $invoice->invoice_number }}

Date: {{ $invoice->created_at->format('d M Y') }}

{{-- ── PATIENT + INSURANCE INFO (two columns) ── --}}
{{-- Patient Information --}}

PATIENT INFORMATION

Patient No.:{{ $patient->mrn ?? '' }}
Full Name:{{ $patient->full_name ?? '' }}
Date of Birth:{{ $patient->date_of_birth ? \Carbon\Carbon::parse($patient->date_of_birth)->format('d M Y') : '-' }}
Gender:{{ ucfirst($patient->gender ?? '-') }}
Clinician:{{ $visit?->clinician?->name ?? '-' }}
Visit Date:{{ $invoice->created_at->format('d M Y, H:i') }}
@if($isInsurance) {{-- Insurance Information --}}

INSURANCE INFORMATION

@if($insurancePayers->count() > 1) @foreach($insurancePayers as $i => $ins) @endforeach @else @endif @if($patient->insurance_scheme ?? null) @endif @if($authCode) @endif {{-- ── SHA member identity ────────────────────────────── Printed inline with the insurer details so SHA can reconcile the claim against the principal's coverage. Falls back to the patient's stored SHA cover when no SHA payment has been recorded yet. --}} @if($shaNumber) @endif @if($shaMemberName) @endif @if($shaRelationship) @endif @if($shaAuthRef) @endif
{{ $i === 0 ? 'Insurers:' : '' }} {{ $ins['name'] }} (KES {{ number_format($ins['amount']) }})
Insurer:{{ $insurerName }}
Scheme/Plan:{{ $patient->insurance_scheme }}
Auth. Code:{{ $authCode }}
SHA No.:{{ $shaNumber }}
Member:{{ $shaMemberName }}
Relationship:{{ $shaRelationship }}
SHA Auth Ref:{{ $shaAuthRef }}
Payer Type:{{ $insurancePayers->count() > 1 ? 'Split / Multiple Insurance' : 'Insurance' }}
@endif
{{-- ── SERVICES RENDERED ── --}}

SERVICES RENDERED

@foreach($invoice->items as $item) @endforeach @if($discount > 0) @endif @if($waiver > 0) @endif
DESCRIPTION UNIT PRICE (KES) QTY TOTAL (KES)
{{ $item->description }} @if($item->category && $item->category !== 'General') · {{ $item->category }} @endif {{ number_format($item->unit_price) }} {{ $item->quantity }} {{ number_format($item->total) }}
Subtotal: {{ number_format($subtotal) }}
Discount{{ $invoice->discount_reason ? ' ('.$invoice->discount_reason.')' : '' }}: - {{ number_format($discount) }}
Waiver{{ $invoice->waiver_reason ? ' ('.$invoice->waiver_reason.')' : '' }}: - {{ number_format($waiver) }}
AMOUNT DUE: KES {{ number_format($grandTotal) }}
{{-- ── PAYER INFORMATION ── --}}

PAYER INFORMATION

@php $payerRowCount = 0; @endphp {{-- Each insurance payer gets its own row with the exact amount --}} @foreach($insurancePayers as $ins) @php $payerRowCount++; @endphp @endforeach {{-- Non-insurance payments already made (cash, mpesa, etc.) --}} @foreach($otherPayers as $oth) @php $payerRowCount++; @endphp @endforeach {{-- Any outstanding patient balance --}} @if($balanceDue > 0) @php $payerRowCount++; @endphp @endif {{-- Fallback: no payers resolved at all — show single cash row --}} @if($payerRowCount === 0) @endif {{-- Total row when there's more than one payer --}} @if($payerRowCount > 1) @endif
PAYER NAME CURRENCY AMOUNT
{{ $payerRowCount === 0 ? 'PLEASE PAY:' : '' }} {{ $ins['name'] }} (Insurance) KES {{ number_format($ins['amount']) }}
{{ $payerRowCount === 0 ? 'PLEASE PAY:' : '' }} {{ $oth['name'] }} KES {{ number_format($oth['amount']) }}
{{ $payerRowCount === 0 ? 'PLEASE PAY:' : 'PATIENT:' }} {{ $patient->full_name ?? 'Patient' }} (Balance) KES {{ number_format($balanceDue) }}
PLEASE PAY: {{ ucfirst($paymentMode) }} KES {{ number_format($grandTotal) }}
TOTAL: KES {{ number_format($insurancePayers->sum('amount') + $otherPayers->sum('amount') + $balanceDue) }}
{{-- ── PAYMENT INFORMATION ── --}}

PAYMENT INFORMATION

Paybill: 522533
Account Number: 6346132
KCB Bank, Clara Rosa Hospital Utawala

{{-- ── SIGNATURE BLOCK ── --}}

Authorized Signature & Stamp

Patient / Guardian Signature

Date

{{-- ── FOOTER ── --}}
Generated: {{ now()->format('d M Y, H:i') }} {{ $hs['hospital_name'] ?? 'Clara Rosa Hospital' }} · This is a computer-generated invoice Page 1 of 1
@endsection