@php
    $branch = $challan->branch;
    $logo = $branch?->logo ? asset('storage/'.ltrim($branch->logo, '/')) : '';
    $family = $challan->family;
    $parentName = $family?->primary_contact_name ?? '-';
    $voucherNo = $challan->challan_number;
    $dueDate = $challan->due_date ?? \Illuminate\Support\Carbon::now();
    $validDate = $dueDate->copy()->addDays(5);
    $netPayable = (float) $challan->net_payable;
    $balance = (float) $challan->balance;
    $afterDue = $balance + (float) $challan->fine_amount;
    $studentNames = $challan->items->map(fn ($i) => $i->student?->name)->filter()->unique()->implode(', ');
    $barcodeUrl = 'https://barcode.tec-it.com/barcode.ashx?data='.urlencode($voucherNo).'&code=Code128&dpi=96&imagetype=Gif&height=42&modulewidth=2&showtext=false';
    $qrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=90x90&qzone=1&data='.urlencode('Challan:'.$voucherNo.' | '.$parentName.' | Rs '.number_format($balance));
    $monthName = fn ($m) => $m >= 1 && $m <= 12 ? date('M', mktime(0, 0, 0, $m, 10)) : '';
@endphp
<div class="sheet-wrap">
  <div class="voucher-sheet">
    @foreach (['Bank Copy', 'School Copy', 'Parent Copy'] as $copyLabel)
      <div class="vc">
        @if($logo)<div class="wm" style="background-image:url('{{ $logo }}')"></div>@endif
        <div class="vc-inner">
          <div class="copy-label">{{ $copyLabel }}</div>

          <div class="vhead">
            @if($logo)<img class="vlogo" src="{{ $logo }}" onerror="this.style.display='none'">@endif
            <div class="vschool">{{ $branch?->name ?? 'School Name' }}</div>
          </div>
          <div class="vaddr">
            {{ trim(($branch?->address ?? '').(($branch?->address && $branch?->city) ? ', ' : '').($branch?->city ?? '')) }}
            @if($branch?->phone)<br>Contact: {{ $branch->phone }}@endif
          </div>

          <table class="vinfo">
            <tr><th>Student:</th><td colspan="3">{{ \Illuminate\Support\Str::limit($studentNames, 70) ?: '-' }}</td></tr>
            <tr><th>Father Name:</th><td>{{ $family?->father_name ?? '-' }}</td><th>Family:</th><td>{{ $family?->family_code }}</td></tr>
            <tr><th>Bill:</th><td>{{ $challan->title }}</td><th>Voucher:</th><td>{{ $voucherNo }}</td></tr>
          </table>

          <div class="vbar"><img src="{{ $barcodeUrl }}" onerror="this.parentNode.style.display='none'"></div>
          @if($family?->family_code)
            <div class="vbank">Family A/C: {{ $family->family_code }} &nbsp; • &nbsp; Payable at {{ $branch?->name ?? 'School' }} Office</div>
          @endif

          <table class="vfee">
            <tr><th class="l">Fee Description</th><th class="r">Amount</th></tr>
            @forelse($challan->items as $item)
              <tr>
                <td class="l">{{ $item->feeType?->name }}</td>
                <td class="r">{{ number_format($item->net) }}</td>
              </tr>
            @empty
              <tr><td class="l">No items</td><td class="r">0</td></tr>
            @endforelse
            <tr class="sub"><td class="l">Net Payable</td><td class="r">{{ number_format($netPayable) }}</td></tr>
          </table>

          <table class="vtot">
            <tr><td class="l">This Challan Payable:</td><td class="r">{{ number_format($balance) }}</td></tr>
            <tr><td class="l">After Due Date:</td><td class="r">{{ number_format($afterDue) }}</td></tr>
            @if($challan->paid_amount > 0)
              <tr><td class="l">Already Paid:</td><td class="r">{{ number_format($challan->paid_amount) }}</td></tr>
            @endif
            @php $outstanding = $familyOutstanding ?? $balance; @endphp
            <tr class="sub"><td class="l">Total Remaining ({{ $outstanding > $balance ? 'All Dues' : 'Payable' }}):</td><td class="r">{{ number_format($outstanding) }}</td></tr>
            <tr><td colspan="2" class="vdates">Issue Date: <b>{{ optional($challan->bill_date)->format('d/m/Y') }}</b> &nbsp; Due Date: <b>{{ $dueDate->format('d/m/Y') }}</b> &nbsp; Printed: <b>{{ now()->format('d/m/Y h:i A') }}</b></td></tr>
          </table>

          @if($challan->relationLoaded('payments') && $challan->payments->isNotEmpty())
            <table class="vfee" style="margin-top:6px">
              <tr><th class="l">Payment Received</th><th class="r">Amount</th></tr>
              @foreach($challan->payments as $pay)
                <tr>
                  <td class="l">{{ $pay->payment_date->format('d/m/Y') }} · {{ $pay->method_label }}</td>
                  <td class="r">{{ number_format($pay->amount) }}</td>
                </tr>
              @endforeach
              <tr class="sub"><td class="l">Balance Remaining</td><td class="r">{{ number_format($challan->balance) }}</td></tr>
            </table>
          @endif

          <div class="vhist-title">Fee History (Family Account)</div>
          <table class="vhist">
            <tr><th>Year</th><th colspan="12">{{ $year }}</th></tr>
            <tr><th>Month</th>@for($m=1;$m<=12;$m++)<td>{{ $monthName($m) }}</td>@endfor</tr>
            <tr><th>Billed</th>@for($m=1;$m<=12;$m++)<td>{{ $billed[$m] ? number_format($billed[$m]) : 0 }}</td>@endfor</tr>
            <tr><th>Paid</th>@for($m=1;$m<=12;$m++)<td>{{ $paid[$m] ? number_format($paid[$m]) : 0 }}</td>@endfor</tr>
          </table>

          <div class="vnotice">
            <div class="vn-text"><b>NOTICE:</b><br>* This is a computer generated fee challan. No manual corrections will be acceptable.</div>
            <div class="vqr"><img src="{{ $qrUrl }}" onerror="this.style.display='none'"></div>
          </div>

          <div class="vsign">
            <span><b>{{ auth()->user()->name }}</b><br>Authorized Signature</span>
            <span>Bank / School Stamp</span>
          </div>
          <div class="vpower">{{ config('app.name') }}</div>
        </div>
      </div>
    @endforeach
  </div>
</div>
