@php
    $customer = $quotation->customer;
    $docOpts = $docSettings['options'] ?? [];
    $docLbl = $docSettings['labels'] ?? [];
    $statusKey = $quotation->status;
    $primarySig = $settings['primary_signature_label'] ?? 'Provider Signature';
    $secondarySig = $settings['secondary_signature_label'] ?? 'Receiver Signature';
    $showTaxable = $settings['show_total_taxable_value'] ?? true;
    $roundOff = $settings['round_off_amount'] ?? false;
    $fmtTotal = function ($n) use ($roundOff) {
        return $roundOff ? number_format(round($n), 0) : number_format($n, 2);
    };
    $billLines = $customer->billingAddressLines();
    $shipLines = $customer->has_shipping_address
        ? $customer->shippingAddressLines()
        : $billLines;
    $totalAmount = (float) $quotation->grand_total;
    $quotationTitle = $quotationTitle ?? \App\Helpers\QuotationDocumentSettings::titleForType($quotation->type, $company->id ?? null);
    $documentCopyLabel = $documentCopyLabel ?? ($documentCopies['original'] ?? 'Original Copy');
    $docId = $docId ?? 'quotation-doc';
    $hasDiscountCol = $quotation->items->contains(fn ($li) => (float) $li->discount_percent > 0);
    $forPdf = $forPdf ?? false;
    if ($forPdf) {
        $logoImage = $logoPath ?? \App\Helpers\CompanyMedia::pdfImagePath($company->logo_path ?? null);
        $signatureImage = $signaturePath ?? \App\Helpers\CompanyMedia::pdfImagePath($company->signature_image_path ?? null);
    } else {
        $logoImage = $logoPath ?? $logoSrc ?? \App\Helpers\CompanyMedia::imageSource($company->logo_path ?? null);
        $signatureImage = $signaturePath ?? $signatureSrc ?? \App\Helpers\CompanyMedia::imageSource($company->signature_image_path ?? null);
    }
@endphp

<div class="billing-invoice-doc{{ ($forPdf ?? false) ? ' billing-invoice-doc--pdf' : '' }}" id="{{ $docId }}" data-layout="{{ $layout ?? 'a4' }}">
    @if(! $forPdf && ! ($forPublic ?? false))
        @if($statusKey === 'accepted')
            <div class="billing-invoice-doc__status-badge billing-invoice-doc__status-badge--paid">Accepted</div>
        @elseif($statusKey === 'rejected')
            <div class="billing-invoice-doc__status-badge billing-invoice-doc__status-badge--overdue">Rejected</div>
        @elseif($statusKey === 'converted')
            <div class="billing-invoice-doc__status-badge billing-invoice-doc__status-badge--paid">Converted</div>
        @elseif($statusKey === 'sent')
            <div class="billing-invoice-doc__status-badge billing-invoice-doc__status-badge--unpaid">Sent</div>
        @endif
    @endif

    <table class="billing-invoice-doc__layout-table billing-invoice-doc__header" width="100%" cellpadding="0" cellspacing="0">
        <tr>
            <td width="58%" valign="top" class="billing-invoice-doc__company">
                @if($logoImage)
                    <img src="{{ $logoImage }}" alt="" class="billing-invoice-doc__logo" width="{{ $forPdf ? 120 : 70 }}">
                @endif
                <h1 class="billing-invoice-doc__company-name">{{ $company->name ?? 'Company' }}</h1>
                @php $companyLines = $company->fullAddressLines(); @endphp
                @if(! empty($companyLines))
                    @foreach($companyLines as $line)
                        <p class="billing-invoice-doc__meta">{{ $line }}</p>
                    @endforeach
                @elseif($company->address ?? $company->city)
                    <p class="billing-invoice-doc__meta">
                        {{ collect([$company->address, $company->city, $company->state, $company->pincode, $company->country])->filter()->implode(', ') }}
                    </p>
                @endif
                @if($company->phone)<p class="billing-invoice-doc__meta">Phone: {{ $company->phone }}</p>@endif
                @if($company->email)<p class="billing-invoice-doc__meta">Email: {{ $company->email }}</p>@endif
                @if($company->gstin ?? null)<p class="billing-invoice-doc__meta"><strong>GSTIN:</strong> {{ $company->gstin }}</p>@endif
            </td>
            <td width="42%" valign="top" align="right" class="billing-invoice-doc__title-block">
                <h2 class="billing-invoice-doc__doc-title">{{ $quotationTitle }}</h2>
                <p class="billing-invoice-doc__doc-number">#{{ $quotation->quote_number }}</p>
                <p class="billing-invoice-doc__copy-label" id="document-copy-label">{{ $documentCopyLabel }}</p>
                @if($docOpts['show_amount_due'] ?? true)
                    <div class="billing-invoice-doc__amount-due">
                        Total: ₹ {{ number_format($totalAmount, 2) }}
                    </div>
                @endif
                <table class="billing-invoice-doc__dates" cellpadding="0" cellspacing="0" align="right">
                    <tr>
                        <td class="billing-invoice-doc__dates-label">Quote Date</td>
                        <td class="billing-invoice-doc__dates-gap" aria-hidden="true">&nbsp;</td>
                        <td class="billing-invoice-doc__dates-value">{{ $quotation->quote_date->format('d - M - Y') }}</td>
                    </tr>
                    <tr>
                        <td class="billing-invoice-doc__dates-label">Valid Until</td>
                        <td class="billing-invoice-doc__dates-gap" aria-hidden="true">&nbsp;</td>
                        <td class="billing-invoice-doc__dates-value">{{ $quotation->valid_until?->format('d - M - Y') ?? '—' }}</td>
                    </tr>
                    @if($quotation->po_no)
                    <tr>
                        <td class="billing-invoice-doc__dates-label">{{ $docLbl['po_number'] ?? ($quotation->po_label ?? 'PO Number') }}</td>
                        <td class="billing-invoice-doc__dates-gap" aria-hidden="true">&nbsp;</td>
                        <td class="billing-invoice-doc__dates-value">{{ $quotation->po_no }}</td>
                    </tr>
                    @endif
                    @if($quotation->po_date)
                    <tr>
                        <td class="billing-invoice-doc__dates-label">PO Date</td>
                        <td class="billing-invoice-doc__dates-gap" aria-hidden="true">&nbsp;</td>
                        <td class="billing-invoice-doc__dates-value">{{ $quotation->po_date->format('d - M - Y') }}</td>
                    </tr>
                    @endif
                    @if(($gstMode ?? false) && ($placeOfSupplyLabel ?? null))
                    <tr>
                        <td class="billing-invoice-doc__dates-label">Place of Supply</td>
                        <td class="billing-invoice-doc__dates-gap" aria-hidden="true">&nbsp;</td>
                        <td class="billing-invoice-doc__dates-value">{{ $placeOfSupplyLabel }}</td>
                    </tr>
                    @endif
                </table>
            </td>
        </tr>
    </table>

    <table class="billing-invoice-doc__layout-table billing-invoice-doc__addresses" width="100%" cellpadding="0" cellspacing="0">
        <tr>
            <td width="{{ ($docOpts['show_shipping_address'] ?? true) ? '50%' : '100%' }}" valign="top">
                <h3 class="billing-invoice-doc__section-label">{{ $docLbl['quote_to'] ?? 'Quote To' }}</h3>
                <p class="billing-invoice-doc__party-name">{{ $customer->name }}</p>
                @if(($docOpts['show_contact_person_quote_to'] ?? true) && $customer->contact_person)
                    <p class="billing-invoice-doc__meta">{{ $customer->contact_person }}</p>
                @endif
                @foreach($billLines as $line)
                    <p class="billing-invoice-doc__meta">{{ $line }}</p>
                @endforeach
                @if($customer->gstin)
                    <p class="billing-invoice-doc__meta"><strong>GSTIN:</strong> {{ $customer->gstin }}</p>
                @endif
            </td>
            @if($docOpts['show_shipping_address'] ?? true)
            <td width="50%" valign="top">
                <h3 class="billing-invoice-doc__section-label">{{ $docLbl['ship_to'] ?? 'Ship To' }}</h3>
                @foreach($shipLines as $line)
                    <p class="billing-invoice-doc__meta">{{ $line }}</p>
                @endforeach
                @if(empty(array_filter($shipLines)))
                    <p class="billing-invoice-doc__meta">Same as billing address</p>
                @endif
            </td>
            @endif
        </tr>
    </table>

    @if($gstMode ?? false)
        @include('partials.admin.document-gst-items', [
            'documentItems' => $quotation->items,
            'gstIsIgst' => $gstIsIgst ?? false,
            'docLbl' => $docLbl,
        ])
    @else
    <table class="billing-invoice-doc__items">
        <thead>
            <tr>
                <th class="col-no">#</th>
                <th class="col-item">{{ $docLbl['col_item'] ?? 'Item' }} &amp; {{ $docLbl['col_description'] ?? 'Description' }}</th>
                <th class="col-qty-uom">Qty / UoM</th>
                <th class="col-price">Price (₹)</th>
                @if($hasDiscountCol)
                    <th class="col-disc">{{ $docLbl['col_discount'] ?? 'Discount' }}</th>
                @endif
                <th class="col-tax">{{ $docLbl['col_tax'] ?? 'Tax' }}</th>
                <th class="col-amt">{{ $docLbl['col_total'] ?? 'Amount' }}</th>
            </tr>
        </thead>
        <tbody>
            @foreach($quotation->items as $i => $line)
            <tr>
                <td>{{ $i + 1 }}</td>
                <td>
                    <span class="item-name">{{ $line->item_name }}</span>
                    @if($line->description)
                        <span class="item-desc">{{ $line->description }}</span>
                    @endif
                </td>
                @php
                    $qtyDisplay = number_format($line->quantity, 0) == $line->quantity
                        ? (string) (int) $line->quantity
                        : number_format($line->quantity, 3);
                    $qtyUom = trim($qtyDisplay . ($line->unit ? ' ' . $line->unit : ''));
                @endphp
                <td class="num col-qty-uom-cell">{{ $qtyUom ?: '—' }}</td>
                <td class="num">{{ number_format($line->rate, 2) }}</td>
                @if($hasDiscountCol)
                    <td class="num">
                        @if((float) $line->discount_percent > 0)
                            {{ rtrim(rtrim(number_format($line->discount_percent, 2), '0'), '.') }}%
                        @else
                            —
                        @endif
                    </td>
                @endif
                <td class="num">
                    @if($line->tax_amount > 0)
                        ₹ {{ number_format($line->tax_amount, 2) }}
                        @if($line->tax_rate > 0)
                            <span class="tax-pct">{{ rtrim(rtrim(number_format($line->tax_rate, 2), '0'), '.') }}%</span>
                        @endif
                    @else
                        —
                    @endif
                </td>
                <td class="num amount">₹ {{ number_format($line->amount, 2) }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @endif

    <table class="billing-invoice-doc__layout-table billing-invoice-doc__bottom" width="100%" cellpadding="0" cellspacing="0">
        <tr>
            <td width="50%" valign="top" class="billing-invoice-doc__bottom-left">
                @include('partials.admin.document-bank-details', [
                    'company' => $company,
                    'settings' => $settings,
                    'showBank' => (bool) ($settings['show_bank_details_quotation'] ?? true),
                ])
                @if($quotation->terms)
                    <div class="billing-invoice-doc__terms">
                        <h3 class="billing-invoice-doc__terms-title">{{ $docLbl['terms'] ?? 'Terms & Conditions' }}</h3>
                        <p>{{ $quotation->terms }}</p>
                    </div>
                @endif
            </td>
            <td width="50%" valign="top">
                @include('partials.admin.document-totals', [
                    'document' => $quotation,
                    'gstMode' => $gstMode ?? false,
                    'gstSummaryRows' => $gstSummaryRows ?? [],
                    'taxBreakdown' => $taxBreakdown ?? [],
                    'showTaxable' => $showTaxable,
                    'fmtTotal' => $fmtTotal,
                    'docOpts' => $docOpts,
                    'docLbl' => $docLbl,
                ])
                @if($docOpts['show_total_in_words'] ?? true)
                    <p class="billing-invoice-doc__words">
                        <strong>Amount in Words:</strong> {{ $amountInWords }}
                    </p>
                @endif
                <table class="billing-invoice-doc__signatures" width="100%" cellpadding="0" cellspacing="0" align="right">
                    <tr>
                        @if($docOpts['show_primary_signature'] ?? true)
                        <td align="right" valign="bottom" class="billing-invoice-doc__signature">
                            @if($signatureImage)
                                <img src="{{ $signatureImage }}" alt="" class="billing-invoice-doc__signature-img" @if($forPdf) width="180" height="118" @else width="180" @endif>
                            @else
                                <div class="billing-invoice-doc__signature-line"></div>
                            @endif
                            <p>{{ $primarySig }}</p>
                        </td>
                        @endif
                        @if($docOpts['show_secondary_signature'] ?? false)
                        <td align="right" valign="bottom" class="billing-invoice-doc__signature">
                            <div class="billing-invoice-doc__signature-line"></div>
                            <p>{{ $secondarySig }}</p>
                        </td>
                        @endif
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>
