{{--
    A4 tax invoice — used identically by the Master Control live preview and
    the real tenant-side print. One blade, both call sites, so the preview is
    what prints. Widths and type sizes are tuned for 210×297mm.

    The live preview passes `preview => true`: the letterhead fields then
    render unconditionally behind data-* markers so the preview bridge can
    repaint them client-side as the landlord types (the print keeps its
    server-side @if guards so an empty field prints nothing, not a blank
    line). Amounts are wrapped in data-inv-amount spans in BOTH modes — the
    markup is shared, so what the bridge reformats is what prints.
--}}
@php
    $isPreview = $preview ?? false;
    $reg = $doc->business->registrationLines();
    $contacts = $doc->business->contactLines();
    $groups = $doc->groupedLines();
    $paidLabel = $doc->isFullyPaid() ? 'Paid' : 'Paid to date';
    $showBalance = $doc->netTotal - $doc->paidAmount > 0.005;
    $branchAddress = $doc->printedBranches()[0]['address'] ?? null;
    $barcode = $doc->barcodeSvg();
@endphp

<style>
    .inv-a4 { --ink: #111827; --muted: #4b5563; --line: #d1d5db; --strong-line: #111827;
        width: 210mm; min-height: 297mm; margin: 0 auto; background: #fff; color: var(--ink);
        font-family: "Segoe UI", system-ui, -apple-system, Arial, sans-serif;
        font-size: 10pt; line-height: 1.45; }
    .inv-a4 * { box-sizing: border-box; }
    .inv-a4 p { margin: 0; }
    .inv-a4 .header { display: flex; justify-content: space-between; align-items: flex-start;
        gap: 16px; padding: 14mm 16mm 0; }
    .inv-a4 .brand { display: flex; gap: 12px; align-items: flex-start; }
    .inv-a4 .logo { width: 22mm; height: 22mm; object-fit: contain; }
    .inv-a4 .monogram { width: 22mm; height: 22mm; display: flex; align-items: center; justify-content: center;
        font-size: 16pt; font-weight: 700; color: #fff; }
    .inv-a4 .brand-name { font-size: 15pt; font-weight: 700; line-height: 1.2; }
    .inv-a4 .tagline { margin-top: 1px; color: var(--muted); font-size: 8.5pt; font-style: italic; }
    .inv-a4 .address { margin-top: 2px; color: var(--muted); }
    .inv-a4 .contact { margin-top: 2px; color: var(--muted); font-size: 8.5pt; }
    .inv-a4 .title-col { text-align: right; }
    .inv-a4 .title { font-size: 17pt; font-weight: 800; letter-spacing: 0.04em; text-transform: uppercase; }
    .inv-a4 .id-box { margin-top: 6px; display: inline-block; text-align: left; font-size: 9pt; }
    .inv-a4 .id-box td { padding: 1px 0 1px 14px; vertical-align: top; }
    .inv-a4 .id-box td.k { color: var(--muted); padding-left: 0; }
    .inv-a4 .meta { display: flex; gap: 6mm; justify-content: space-between; margin: 7mm 16mm 0; }
    .inv-a4 .meta-box { flex: 1; border: 1px solid var(--line); padding: 3mm 4mm; font-size: 8.5pt; }
    .inv-a4 .meta-box h3 { margin: 0 0 2px; font-size: 8pt; text-transform: uppercase; letter-spacing: 0.05em;
        color: var(--muted); font-weight: 600; }
    .inv-a4 .meta-box .lbl { color: var(--muted); }
    .inv-a4 .table-wrap { margin: 6mm 16mm 0; }
    .inv-a4 table.items { width: 100%; border-collapse: collapse; font-size: 8.5pt; }
    .inv-a4 table.items thead th { border-top: 2px solid var(--strong-line); border-bottom: 1px solid var(--strong-line);
        padding: 2mm 2mm; text-align: left; font-size: 8pt; text-transform: uppercase; letter-spacing: 0.05em; }
    .inv-a4 table.items thead th.r, .inv-a4 table.items tbody td.r { text-align: right; }
    .inv-a4 table.items thead th.c, .inv-a4 table.items tbody td.c { text-align: center; }
    .inv-a4 table.items td { padding: 1.8mm 2mm; border-bottom: 1px solid #e5e7eb; vertical-align: top; }
    .inv-a4 table.items tr.bundle-row td { background: #f9fafb; font-weight: 600; font-size: 8.5pt;
        border-bottom: 1px solid var(--line); }
    .inv-a4 .line-name { font-weight: 600; }
    .inv-a4 .line-sub { color: var(--muted); font-size: 7.5pt; }
    .inv-a4 .totals { margin-top: 5mm; display: flex; gap: 12mm; justify-content: flex-end; }
    .inv-a4 .totals table { border-collapse: collapse; font-size: 9pt; }
    .inv-a4 .totals td { padding: 1.2mm 2mm; }
    .inv-a4 .totals td.k { color: var(--muted); text-align: right; }
    .inv-a4 .totals td.v { text-align: right; white-space: nowrap; }
    .inv-a4 .totals tr.disc td.v { color: #b91c1c; }
    .inv-a4 .totals .grand td { border-top: 2px solid var(--strong-line); font-size: 11.5pt; font-weight: 700; }
    .inv-a4 .totals .grand td.k { color: var(--ink); }
    .inv-a4 .amount-words { margin: 4mm 16mm 0; font-size: 8.5pt; color: var(--muted); }
    .inv-a4 .amount-words b { color: var(--ink); }
    .inv-a4 .pay { margin: 6mm 16mm 0; border: 1px solid var(--line); }
    .inv-a4 .pay h3 { margin: 0; padding: 2mm 4mm; font-size: 8pt; text-transform: uppercase; letter-spacing: 0.05em;
        color: var(--muted); font-weight: 600; border-bottom: 1px solid var(--line); }
    .inv-a4 .pay table { width: 100%; border-collapse: collapse; font-size: 8.5pt; }
    .inv-a4 .pay td { padding: 1.8mm 4mm; border-bottom: 1px solid #f3f4f6; }
    .inv-a4 .pay td.amt { text-align: right; white-space: nowrap; }
    .inv-a4 .pay .pending { color: #b45309; }
    .inv-a4 .balance-box { display: flex; justify-content: space-between; align-items: center; padding: 3mm 4mm;
        background: #f8fafc; font-size: 10.5pt; font-weight: 700; }
    .inv-a4 .note { margin: 5mm 16mm 0; border-top: 1px solid var(--line); padding-top: 3mm; font-size: 8pt; color: var(--muted); }
    .inv-a4 .note b { color: var(--ink); }
    .inv-a4 .sample-strip { background: #fff7ed; border-top: 2px solid #fb923c; padding: 2.5mm 16mm; font-size: 8pt; }
    .inv-a4 .sample-strip p { margin: 0; color: #9a3412; }
    .inv-a4 .footer { margin: 5mm 16mm 0; border-top: 1px solid var(--line); padding-top: 2.5mm;
        text-align: center; font-size: 7.5pt; color: var(--muted); }
    .inv-a4 .footer p { margin: 0; }

    /* The bottom half is one positioned context so the PAID seal can sit
       punched over the total and payments, the way a real stamp lands on the
       payable figure. The seal itself lives in a shared partial; this layout
       only places and sizes it. */
    .inv-a4 .bottom { position: relative; }
    .inv-a4 .paid-seal { position: absolute; top: -2mm; right: 6mm; width: 58mm;
        transform: rotate(-7deg); transform-origin: center; }

    .inv-a4 .barcode { margin-top: 3mm; text-align: right; }
    .inv-a4 .barcode svg { width: 42mm; height: 12mm; }
</style>

<div class="inv-a4">
    <div class="header">
        <div class="brand">
            @if ($doc->business->logo !== null)
                <img class="logo" src="{{ $doc->business->logo }}" alt="" />
            @else
                <div class="monogram" style="background: #2563eb">{{ $doc->business->monogram() }}</div>
            @endif

            <div>
                <p class="brand-name" data-inv-bind="business_name">{{ $doc->business->displayName() }}</p>
                @if ($isPreview || $doc->business->description !== null)
                    <p class="tagline" data-inv-bind="business_description">{{ $doc->business->description }}</p>
                @endif
                @if ($isPreview || $doc->business->address !== null)
                    <p class="address" data-inv-bind="business_address">{{ $doc->business->address }}</p>
                @endif
                @if (! empty($branchAddress))
                    <p class="address">{{ $branchAddress }}</p>
                @endif
                @if ($isPreview)
                    <p class="contact" data-inv-bind="business_phone" data-inv-prefix="Tel: ">Tel: {{ $doc->business->phone }}</p>
                    <p class="contact" data-inv-bind="business_email" data-inv-prefix="Email: ">Email: {{ $doc->business->email }}</p>
                    <p class="contact" data-inv-bind="business_website" data-inv-prefix="Web: ">Web: {{ $doc->business->website }}</p>
                @else
                    @foreach ($contacts as $contact)
                        <p class="contact">{{ $contact['label'] }}: {{ $contact['value'] }}</p>
                    @endforeach
                @endif
                @if ($isPreview)
                    {{-- One line in the print, rebuilt whole by the bridge so
                         the " · " separator only shows when both sides exist. --}}
                    <p class="contact" data-inv-reg="1">
                        Reg. No: {{ $doc->business->registrationNo }} · VAT/TIN: {{ $doc->business->taxRegistrationNo }}
                    </p>
                @elseif ($reg !== [])
                    <p class="contact">
                        @foreach ($reg as $line)
                            {{ $line['label'] }}: {{ $line['value'] }}@if (! $loop->last) &nbsp;·&nbsp; @endif
                        @endforeach
                    </p>
                @endif
            </div>
        </div>

        <div class="title-col">
            <p class="title" data-inv-title="1">{{ $doc->title() }}</p>
            <table class="id-box">
                @if ($doc->physicalReference !== null)
                    <tr><td class="k">Book ref</td><td>{{ $doc->physicalReference }}</td></tr>
                @endif
                <tr><td class="k">Date</td><td>{{ $doc->issuedAt }}</td></tr>
                <tr><td class="k">Invoice No.</td><td><b>{{ $doc->number }}</b></td></tr>
            </table>
            @if ($barcode !== '')
                <div class="barcode">{!! $barcode !!}</div>
            @endif
        </div>
    </div>

    <div class="meta">
        @if (! empty($doc->customer['isRegistered']))
            <div class="meta-box">
                <h3>Sold To</h3>
                <p><b>{{ $doc->customer['name'] }}</b></p>
                @if (! empty($doc->customer['address']))
                    <p>{{ $doc->customer['address'] }}</p>
                @endif
                @foreach (['phone' => 'Tel', 'email' => 'Email', 'nic' => 'NIC'] as $key => $label)
                    @if (! empty($doc->customer[$key]))
                        <p><span class="lbl">{{ $label }}:</span> {{ $doc->customer[$key] }}</p>
                    @endif
                @endforeach
            </div>

            @if (! empty($doc->customer['deliveryAddress']))
                <div class="meta-box">
                    <h3>Deliver To</h3>
                    <p><b>{{ $doc->customer['name'] }}</b></p>
                    <p>{{ $doc->customer['deliveryAddress'] }}</p>
                </div>
            @endif
        @endif

        <div class="meta-box">
            <h3>Details</h3>
            @if (! empty($doc->meta['branch']))
                <p><span class="lbl">Branch:</span> {{ $doc->meta['branch'] }}</p>
            @endif
            @if (! empty($doc->meta['rep']))
                <p><span class="lbl">Sales rep:</span> {{ $doc->meta['rep'] }}</p>
            @endif
            @if ($doc->paymentStatus !== null)
                <p><span class="lbl">Payment:</span> {{ $doc->paymentStatus }}</p>
            @endif
        </div>
    </div>

    <div class="table-wrap">
        <table class="items">
            <thead>
                <tr>
                    <th style="width:52%">Item</th>
                    <th class="c" style="width:9%">Qty</th>
                    <th class="r" style="width:12%">Unit Price</th>
                    <th class="r" style="width:12%">Discount</th>
                    <th class="r" style="width:15%">Amount</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($groups as $group)
                    @if ($group['bundle'] !== null)
                        <tr class="bundle-row">
                            <td colspan="5">{{ $group['bundle'] }}</td>
                        </tr>
                    @endif

                    @foreach ($group['lines'] as $line)
                        <tr>
                            <td>
                                <p class="line-name">{{ $line->name }}</p>
                                @if ($line->sku !== null)
                                    <p class="line-sub">SKU {{ $line->sku }}</p>
                                @endif
                                @foreach ($line->traceLines() as $trace)
                                    <p class="line-sub">{{ $trace }}</p>
                                @endforeach
                            </td>
                            <td class="c">{{ $line->quantityLabel() }}</td>
                            <td class="r"><span data-inv-amount="{{ $line->unitPrice }}" data-inv-symbol="1">{{ $doc->money($line->unitPrice) }}</span></td>
                            <td class="r">
                                @if ($line->hasDiscount())
                                    {{ $line->discountLabel() }}
                                    <span class="line-sub" data-inv-amount="{{ $line->discountAmount }}" data-inv-symbol="1">{{ $doc->money($line->discountAmount) }}</span>
                                @endif
                            </td>
                            <td class="r"><span data-inv-amount="{{ $line->lineTotal }}" data-inv-symbol="1">{{ $doc->money($line->lineTotal) }}</span></td>
                        </tr>
                    @endforeach
                @endforeach
            </tbody>
        </table>
    </div>

    <div class="bottom">
        <div class="totals">
        <table>
            <tr>
                <td class="k">Subtotal (gross)</td>
                <td class="v"><span data-inv-amount="{{ $doc->grossSubtotal }}" data-inv-symbol="1">{{ $doc->money($doc->grossSubtotal) }}</span></td>
            </tr>
            @if ($doc->lineDiscountTotal > 0)
                <tr class="disc">
                    <td class="k">Line discounts</td>
                    <td class="v">− <span data-inv-amount="{{ $doc->lineDiscountTotal }}" data-inv-symbol="1">{{ $doc->money($doc->lineDiscountTotal) }}</span></td>
                </tr>
            @endif
            @if ($doc->invoiceDiscountTotal > 0)
                @forelse ($doc->discountBreakdown as $discount)
                    <tr class="disc">
                        <td class="k">{{ $discount['label'] }}</td>
                        <td class="v">− <span data-inv-amount="{{ $discount['amount'] }}" data-inv-symbol="1">{{ $doc->money($discount['amount']) }}</span></td>
                    </tr>
                @empty
                    <tr class="disc">
                        <td class="k">Invoice discount</td>
                        <td class="v">− <span data-inv-amount="{{ $doc->invoiceDiscountTotal }}" data-inv-symbol="1">{{ $doc->money($doc->invoiceDiscountTotal) }}</span></td>
                    </tr>
                @endforelse
            @endif
            @if ($doc->hasVatBreakdown())
                @foreach ($doc->vatBreakdown as $vat)
                    <tr>
                        <td class="k">VAT @ {{ rtrim(rtrim(number_format($vat['rate'], 2, '.', ''), '0'), '.') }}%</td>
                        <td class="v"><span data-inv-amount="{{ $vat['vat'] }}" data-inv-symbol="1">{{ $doc->money($vat['vat']) }}</span></td>
                    </tr>
                @endforeach
            @elseif ($doc->business->vatEnabled && $doc->vatTotal > 0)
                <tr>
                    <td class="k">VAT</td>
                    <td class="v"><span data-inv-amount="{{ $doc->vatTotal }}" data-inv-symbol="1">{{ $doc->money($doc->vatTotal) }}</span></td>
                </tr>
            @endif
            <tr class="grand">
                <td class="k">Total Payable</td>
                <td class="v"><span data-inv-amount="{{ $doc->netTotal }}" data-inv-symbol="1">{{ $doc->money($doc->netTotal) }}</span></td>
            </tr>
        </table>
    </div>

    <div class="amount-words">
        Amount in words: <b>{{ $doc->amountInWords() }}</b>
    </div>

    @if ($doc->payments !== [])
        <div class="pay">
            <h3>Payments</h3>
            <table>
                @foreach ($doc->payments as $payment)
                    <tr>
                        <td>
                            {{ $payment['method'] }}
                            @if ($payment['reference'] !== null)
                                <span style="color:var(--muted)"> — {{ $payment['reference'] }}</span>
                            @endif
                        </td>
                        <td class="amt">
                            <span data-inv-amount="{{ $payment['amount'] }}" data-inv-symbol="1">{{ $doc->money($payment['amount']) }}</span>
                            @if ($payment['pending'])
                                <span class="pending">(pending)</span>
                            @endif
                        </td>
                    </tr>
                @endforeach
            </table>
            <div class="balance-box">
                <span>{{ $paidLabel }}</span>
                <span><span data-inv-amount="{{ $doc->paidAmount }}" data-inv-symbol="1">{{ $doc->money($doc->paidAmount) }}</span></span>
            </div>
            @if ($doc->hasChangeReturned())
                <div class="balance-box">
                    <span>Tendered</span>
                    <span><span data-inv-amount="{{ $doc->tenderedAmount }}" data-inv-symbol="1">{{ $doc->money((float) $doc->tenderedAmount) }}</span></span>
                </div>
                <div class="balance-box">
                    <span>Change given</span>
                    <span><span data-inv-amount="{{ $doc->changeAmount }}" data-inv-symbol="1">{{ $doc->money((float) $doc->changeAmount) }}</span></span>
                </div>
            @endif
            @if ($showBalance)
                <div class="balance-box">
                    <span>Balance due</span>
                    <span><span data-inv-amount="{{ $doc->balance }}" data-inv-symbol="1">{{ $doc->money($doc->balance) }}</span></span>
                </div>
            @endif
        </div>
    @endif

        @if ($doc->isFullyPaid())
            {{-- Ink-struck over the payable figure — the paper kind of
                 reassurance only a fully settled invoice earns. --}}
            @include('invoices.print.partials.paid-seal', [
                'sealDate' => $doc->issuedAt,
            ])
        @endif
    </div>

    @if ($doc->note !== null)
        <div class="note">
            <b>Notes:</b> {{ $doc->note }}
        </div>
    @endif

    @if ($doc->isSample)
        <div class="sample-strip">
            <p>SAMPLE — this is a worst-case example invoice shown as a live preview. Nothing on it was sold.</p>
        </div>
    @endif

    <div class="footer">
        <p>Software by Vellix Global &middot; Call Us: +94 77 320 8478 &middot; +94 76 375 5374</p>
    </div>
</div>
