@php
    $businessLogo = \App\Models\BusinessSetting::where(['key' => 'logo'])->first();
    $businessName = \App\CentralLogics\Helpers::get_business_data('business_name') ?? config('app.name');
    $footerText = \App\CentralLogics\Helpers::get_business_data('footer_text');
    $businessLogoUrl = $businessLogo?->value
        ? \App\CentralLogics\Helpers::get_full_url('business', $businessLogo?->value, $businessLogo?->storage[0]?->value ?? 'public')
        : asset('/public/assets/admin/img/invoice-logo.png');
    $shipment = \Illuminate\Support\Facades\Schema::hasTable('order_courier_shipments') ? $order->courierShipment : null;
    $deliveryAddress = json_decode($order->getRawOriginal('delivery_address') ?: '[]', true);
    $receiverDetails = is_array($order->receiver_details)
        ? $order->receiver_details
        : json_decode($order->getRawOriginal('receiver_details') ?: '[]', true);
    $courierParcelIdCandidates = [
        $shipment?->courier_parcel_id,
        $shipment?->courier_consignment_id,
        $shipment?->courier_tracking_id,
        data_get($receiverDetails, 'parcel_id'),
        data_get($receiverDetails, 'parcelId'),
        data_get($receiverDetails, 'tracking_id'),
        data_get($receiverDetails, 'trackingId'),
        data_get($receiverDetails, 'consignment_id'),
        data_get($receiverDetails, 'consignmentId'),
        data_get($receiverDetails, 'shipment_id'),
        data_get($receiverDetails, 'shipmentId'),
        data_get($receiverDetails, 'courier_parcel_id'),
        data_get($receiverDetails, 'courierParcelId'),
        data_get($deliveryAddress, 'parcel_id'),
        data_get($deliveryAddress, 'parcelId'),
        data_get($deliveryAddress, 'tracking_id'),
        data_get($deliveryAddress, 'trackingId'),
        data_get($deliveryAddress, 'consignment_id'),
        data_get($deliveryAddress, 'consignmentId'),
        data_get($deliveryAddress, 'shipment_id'),
        data_get($deliveryAddress, 'shipmentId'),
        data_get($deliveryAddress, 'courier_parcel_id'),
        data_get($deliveryAddress, 'courierParcelId'),
    ];
    if (filled($order->transaction_reference) && $order->order_type === 'parcel') {
        $courierParcelIdCandidates[] = $order->transaction_reference;
    }
    $courierParcelId   = collect($courierParcelIdCandidates)->first(fn($v) => filled($v));
    $courierTrackingId = $shipment?->courier_tracking_id;

    $customerFullName    = trim(implode(' ', array_filter([data_get($order,'customer.f_name'), data_get($order,'customer.l_name')])));
    $orderAddressFullName= trim(implode(' ', array_filter([data_get($order,'address.f_name'), data_get($order,'address.l_name')])));
    $fallbackContactName = $customerFullName ?: $orderAddressFullName;
    $fallbackPhone       = data_get($order,'customer.phone') ?: data_get($order,'address.phone') ?: data_get($order,'address.contact_person_number');
    $fallbackAddressText = data_get($deliveryAddress,'address') ?: data_get($order,'address.address') ?: '';
    $senderName    = data_get($deliveryAddress,'contact_person_name') ?: $fallbackContactName;
    $senderPhone   = data_get($deliveryAddress,'contact_person_number') ?: $fallbackPhone;
    $senderAddress = data_get($deliveryAddress,'address') ?: $fallbackAddressText;
    $receiverName    = data_get($receiverDetails,'contact_person_name') ?: $fallbackContactName;
    $receiverPhone   = data_get($receiverDetails,'contact_person_number') ?: $fallbackPhone;
    $receiverAddress = data_get($receiverDetails,'address') ?: '';
@endphp

<style>
/* ── A5 page size ────────────────────────────────────── */
@page {
    size: A5 portrait;
    margin: 5mm 6mm;
}

/* ── Reset for print context ────────────────────────── */
@media print {
    html, body {
        width: 136mm !important;
        max-width: 136mm !important;
        min-width: 0 !important;
        height: auto !important;
        min-height: 0 !important;
        overflow: visible !important;
        background: #fff !important;
        margin: 0 !important;
        padding: 0 !important;
    }
    /* Hide the admin shell – only invoice content prints */
    .navbar, .sidebar, header, footer, aside,
    .hs-unfold, .page-header, .content-wrapper > *:not(.invoice-page),
    .non-printable { display: none !important; }
    .content-wrapper, .main-content,
    .content.container-fluid,
    .invoice-page {
        padding: 0 !important;
        margin: 0 !important;
        width: 100% !important;
        max-width: 100% !important;
        background: #fff !important;
    }
    #printableArea {
        width: 100% !important;
    }
    .inv-wrap {
        width: 100% !important;
    }
    .inv-card {
        border: none !important;
        box-shadow: none !important;
        padding: 0 !important;
    }
    .inv-footer {
        margin-top: 12px !important;
    }
    .inv-tbl thead th { background: #f3f4f6 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    .inv-parcel-box   { background: #eff6ff !important; border: 1.5px solid #93c5fd !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    .inv-summary-row.paid   { color: #16a34a !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    .inv-summary-row.due    { color: #dc2626 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    tr { page-break-inside: avoid; }
}

/* ── Base ────────────────────────────────────────────── */
.invoice-page * {
    box-sizing: border-box;
    font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
}
.invoice-page {
    background: #f1f5f9;
    padding: 20px 0 40px;
}

/* ── Toolbar ─────────────────────────────────────────── */
.inv-toolbar {
    text-align: center;
    margin-bottom: 16px;
}

/* ── Card ────────────────────────────────────────────── */
.inv-wrap {
    width: 100%;
    max-width: 100%;
    margin: 0;
}
.inv-card {
    background: #fff;
    border: 1px solid #d1d9e0;
    border-radius: 10px;
    padding: 12px 14px 10px;
    box-shadow: 0 4px 18px rgba(0,0,0,.07);
}

/* ── Header ──────────────────────────────────────────── */
.inv-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 12px;
    padding-bottom: 10px;
    border-bottom: 2px solid #1e293b;
    margin-bottom: 10px;
}
.inv-brand { display: flex; align-items: flex-start; gap: 10px; min-width: 0; }
.inv-logo  { height: 60px; width: auto; max-width: 130px; object-fit: contain; }
.inv-brand-info {}
.inv-label {
    font-size: 10px;
    font-weight: 800;
    letter-spacing: .12em;
    text-transform: uppercase;
    color: #64748b;
    margin: 0 0 2px;
}
.inv-biz-name {
    font-size: 19px;
    font-weight: 800;
    color: #0f172a;
    margin: 0 0 2px;
    line-height: 1.1;
}
.inv-biz-sub {
    font-size: 12px;
    font-weight: 600;
    color: #475569;
    line-height: 1.4;
    margin: 0;
}
.inv-meta {
    text-align: right;
    flex-shrink: 0;
}
.inv-meta table { border-collapse: collapse; }
.inv-meta td {
    font-size: 12px;
    font-weight: 600;
    color: #475569;
    padding: 1px 0 1px 8px;
    white-space: nowrap;
    vertical-align: top;
}
.inv-meta td.lbl { text-align: right; }
.inv-meta td.val { font-weight: 800; color: #0f172a; text-align: right; }

/* ── Parcel ID box ───────────────────────────────────── */
.inv-parcel-box {
    display: flex;
    align-items: center;
    gap: 10px;
    background: #eff6ff;
    border: 1.5px solid #93c5fd;
    border-radius: 7px;
    padding: 7px 10px;
    margin-bottom: 10px;
}
.inv-parcel-label {
    font-size: 10px;
    font-weight: 800;
    letter-spacing: .1em;
    text-transform: uppercase;
    color: #1d4ed8;
    white-space: nowrap;
}
.inv-parcel-value {
    font-size: 16px;
    font-weight: 800;
    color: #0f172a;
    word-break: break-all;
}
.inv-parcel-track {
    font-size: 12px;
    font-weight: 600;
    color: #1d4ed8;
    margin-top: 2px;
}

/* ── Section title ───────────────────────────────────── */
.inv-section-title {
    font-size: 10px;
    font-weight: 800;
    letter-spacing: .1em;
    text-transform: uppercase;
    color: #64748b;
    margin: 0 0 5px;
    padding-bottom: 3px;
    border-bottom: 1px solid #e2e8f0;
}

/* ── Info rows ───────────────────────────────────────── */
.inv-info-grid {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 1px 8px;
    margin-bottom: 10px;
}
.inv-info-key {
    font-size: 12px;
    color: #64748b;
    white-space: nowrap;
    font-weight: 700;
}
.inv-info-val {
    font-size: 12px;
    font-weight: 600;
    color: #0f172a;
    word-break: break-word;
}

/* ── 2-col info (parcel sender/receiver) ─────────────── */
.inv-two-col {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-bottom: 10px;
}
.inv-info-box {
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    padding: 6px 8px;
}
.inv-info-box .inv-section-title { border-bottom: none; margin-bottom: 4px; }

/* ── Product table ───────────────────────────────────── */
.inv-tbl {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
    margin-bottom: 8px;
}
.inv-tbl thead tr {
    border-top: 1px solid #cbd5e1;
    border-bottom: 1px solid #cbd5e1;
}
.inv-tbl thead th {
    font-size: 9px;
    font-weight: 800;
    letter-spacing: .07em;
    text-transform: uppercase;
    color: #475569;
    background: #f8fafc;
    padding: 5px 3px;
    overflow: hidden;
}
.inv-tbl tbody td {
    font-size: 11px;
    font-weight: 600;
    color: #0f172a;
    padding: 5px 3px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: top;
    overflow: hidden;
}
.inv-tbl tbody tr:last-child td { border-bottom: none; }
.inv-tbl .col-item  { text-align: left; }
.inv-tbl .col-qty   { text-align: center; width: 26px; }
.inv-tbl .col-price { text-align: right; white-space: nowrap; width: 55px; }
.inv-tbl .col-disc  { text-align: right; white-space: nowrap; width: 50px; color: #dc2626; }
.inv-tbl .col-total { text-align: right; white-space: nowrap; width: 58px; }
.inv-item-name  { font-weight: 700; line-height: 1.3; word-break: break-word; }
.inv-item-meta  { font-size: 9px; font-weight: 600; color: #64748b; margin-top: 1px; }
.inv-item-addon { font-size: 9px; font-weight: 600; color: #475569; margin-top: 1px; }
.inv-item-disc  { font-size: 9px; font-weight: 600; color: #dc2626; margin-top: 1px; }

/* ── Summary ─────────────────────────────────────────── */
.inv-summary {
    border-top: 1px solid #cbd5e1;
    padding-top: 7px;
    margin-top: 4px;
}
.inv-summary-row {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    font-size: 13px;
    font-weight: 600;
    color: #334155;
    padding: 2px 0;
}
.inv-summary-row.discount { color: #dc2626; }
.inv-summary-row.coupon   { color: #dc2626; }
.inv-summary-row.paid     { color: #16a34a; font-weight: 700; }
.inv-summary-row.due      { color: #dc2626; font-weight: 800; border-top: 1px dashed #fca5a5; padding-top: 4px; margin-top: 2px; }
.inv-summary-row.total {
    font-size: 15px;
    font-weight: 800;
    color: #0f172a;
    border-top: 1.5px solid #1e293b;
    margin-top: 4px;
    padding-top: 5px;
}
.inv-summary-lbl { color: inherit; }
.inv-summary-val { font-weight: 700; white-space: nowrap; }
.inv-summary-row.total .inv-summary-val { font-weight: 800; }

/* ── Payment note ────────────────────────────────────── */
.inv-payment-note {
    font-size: 12px;
    font-weight: 600;
    color: #475569;
    border-top: 1px solid #e2e8f0;
    margin-top: 6px;
    padding-top: 5px;
}

/* ── Footer ──────────────────────────────────────────── */
.inv-footer {
    text-align: center;
    border-top: 1px solid #e2e8f0;
    margin-top: 12px;
    padding-top: 8px;
}
.inv-footer-ty {
    font-size: 15px;
    font-weight: 800;
    letter-spacing: .08em;
    text-transform: uppercase;
    color: #0f172a;
    margin: 0 0 2px;
}
.inv-footer-copy { font-size: 12px; font-weight: 600; color: #64748b; margin: 0; }
.inv-footer-web  { font-size: 12px; font-weight: 700; color: #1d4ed8; margin: 3px 0 0; letter-spacing: .02em; }
</style>

<div class="content container-fluid invoice-page">
  <div id="printableArea">
    <div class="inv-wrap">

      {{-- Toolbar (screen only) --}}
      <div class="inv-toolbar non-printable">
        <input type="button" class="btn btn-primary"
               onclick="printDiv('printableArea')"
               value="{{ translate('messages.print_invoice') }}">
        <a href="{{ url()->previous() }}" class="btn btn-danger ml-2">{{ translate('messages.back') }}</a>
      </div>

      <div class="inv-card">

        {{-- ── Header ──────────────────────────────── --}}
        <div class="inv-header">
          <div class="inv-brand">
            <img class="inv-logo" src="{{ $businessLogoUrl }}" alt="{{ $businessName }}">
            <div class="inv-brand-info">
              <p class="inv-label">{{ translate('Order Invoice') }}</p>
              <p class="inv-biz-name">{{ $businessName }}</p>
              @if ($order->store?->name)
                <p class="inv-biz-sub">{{ $order->store->name }}</p>
              @endif
              @if ($order->store?->address)
                <p class="inv-biz-sub">{{ $order->store->address }}</p>
              @endif
              @if ($order->store?->phone)
                <p class="inv-biz-sub">{{ translate('messages.phone') }}: {{ $order->store->phone }}</p>
              @endif
            </div>
          </div>
          <div class="inv-meta">
            <table>
              <tr>
                <td class="lbl">{{ translate('order_id') }}</td>
                <td class="val">&nbsp;#{{ $order['id'] }}</td>
              </tr>
              <tr>
                <td class="lbl">{{ translate('invoice_Date') }}</td>
                <td class="val">&nbsp;{{ date('d M Y', strtotime($order['created_at'])) }}</td>
              </tr>
              <tr>
                <td class="lbl">{{ translate('messages.time') }}</td>
                <td class="val">&nbsp;{{ date(config('timeformat'), strtotime($order['created_at'])) }}</td>
              </tr>
              @if ($order->store?->gst_status)
                <tr>
                  <td class="lbl">{{ translate('Gst No') }}</td>
                  <td class="val">&nbsp;{{ $order->store->gst_code }}</td>
                </tr>
              @endif
              @if (filled($order['transaction_reference']) && $order['transaction_reference'] !== $courierParcelId)
                <tr>
                  <td class="lbl">{{ translate('messages.reference_code') }}</td>
                  <td class="val">&nbsp;{{ $order['transaction_reference'] }}</td>
                </tr>
              @endif
              <tr>
                <td class="lbl">{{ translate('messages.payment') }}</td>
                <td class="val">&nbsp;{{ translate('messages.' . $order->payment_method) }}</td>
              </tr>
            </table>
          </div>
        </div>

        {{-- ── Parcel ID (if present) ──────────────── --}}
        @if ($courierParcelId || $courierTrackingId)
          <div class="inv-parcel-box">
            <div>
              <div class="inv-parcel-label">{{ translate('Parcel ID') }}</div>
              @if ($courierParcelId)
                <div class="inv-parcel-value">{{ $courierParcelId }}</div>
              @endif
              @if ($courierTrackingId && $courierTrackingId !== $courierParcelId)
                <div class="inv-parcel-track">{{ translate('Tracking') }}: {{ $courierTrackingId }}</div>
              @endif
            </div>
          </div>
        @endif

        {{-- ── Customer / Delivery Info ────────────── --}}
        @if ($order->order_type == 'parcel')
          <div class="inv-two-col">
            <div class="inv-info-box">
              <div class="inv-section-title">{{ translate('messages.sender_info') }}</div>
              <div class="inv-info-grid">
                <span class="inv-info-key">{{ translate('messages.name') }}</span><span class="inv-info-val">{{ $senderName }}</span>
                <span class="inv-info-key">{{ translate('messages.phone') }}</span><span class="inv-info-val">{{ $senderPhone }}</span>
                @if ($senderAddress)
                  <span class="inv-info-key">{{ translate('messages.address') }}</span><span class="inv-info-val">{{ $senderAddress }}</span>
                @endif
              </div>
            </div>
            <div class="inv-info-box">
              <div class="inv-section-title">{{ translate('messages.receiver_info') }}</div>
              <div class="inv-info-grid">
                <span class="inv-info-key">{{ translate('messages.name') }}</span><span class="inv-info-val">{{ $receiverName }}</span>
                <span class="inv-info-key">{{ translate('messages.phone') }}</span><span class="inv-info-val">{{ $receiverPhone }}</span>
                @if ($receiverAddress)
                  <span class="inv-info-key">{{ translate('messages.address') }}</span><span class="inv-info-val">{{ $receiverAddress }}</span>
                @endif
              </div>
            </div>
          </div>
        @else
          @if ($senderName || $senderPhone || $senderAddress || $fallbackContactName || $fallbackPhone)
            <div class="inv-section-title">{{ translate('messages.delivery_info') }}</div>
            <div class="inv-info-grid" style="margin-bottom:10px">
              @if ($senderName || $fallbackContactName)
                <span class="inv-info-key">{{ translate('messages.name') }}</span>
                <span class="inv-info-val">{{ $senderName ?: $fallbackContactName }}</span>
              @endif
              @if ($senderPhone || $fallbackPhone)
                <span class="inv-info-key">{{ translate('messages.phone') }}</span>
                <span class="inv-info-val">{{ $senderPhone ?: $fallbackPhone }}</span>
              @endif
              @php
                // Load customer address record for fallback fields
                $custAddr    = $order->delivery_address_id
                               ? \App\Models\CustomerAddress::find($order->delivery_address_id)
                               : null;
                $districtVal = data_get($deliveryAddress,'district') ?: ($custAddr?->district ?? null);
                $thanaVal    = data_get($deliveryAddress,'thana')     ?: ($custAddr?->thana ?? null);
                // additional_information: JSON first, then customer_addresses row
                $addlInfo    = data_get($deliveryAddress,'additional_information')
                               ?: ($custAddr?->additional_information ?? null);
                // Show raw address only when meaningful (not just 'N' or very short)
                $addrDisplay = strlen(trim($senderAddress)) > 2 ? $senderAddress : null;
              @endphp
              {{-- Address Details (additional_information) takes priority over raw 'address' --}}
              @if ($addlInfo)
                <span class="inv-info-key">{{ translate('messages.address') }}</span>
                <span class="inv-info-val">{{ $addlInfo }}</span>
              @elseif ($addrDisplay)
                <span class="inv-info-key">{{ translate('messages.address') }}</span>
                <span class="inv-info-val">{{ $addrDisplay }}</span>
              @endif
              @if ($districtVal)
                <span class="inv-info-key">{{ translate('District') }}</span>
                <span class="inv-info-val">{{ $districtVal }}{{ $thanaVal ? ', '.$thanaVal : '' }}</span>
              @endif
            </div>
          @endif
        @endif

        {{-- ── Product Table ────────────────────────── --}}
        <div class="inv-section-title">{{ translate('messages.items') }}</div>
        <table class="inv-tbl">
          <thead>
            <tr>
              <th class="col-item">#&nbsp;{{ translate('messages.item') }}</th>
              <th class="col-qty">{{ translate('messages.qty') }}</th>
              <th class="col-price">{{ translate('MRP') }}</th>
              <th class="col-disc">{{ translate('messages.discount') }}</th>
              <th class="col-total">{{ translate('messages.total') }}</th>
            </tr>
          </thead>
          <tbody>
            @php
                $sub_total = 0;
                $total_tax = 0;
                $add_ons_cost = 0;
                $total_item_discount = 0;
                $fallback_delivery_charge = 0;
                $fallback_packaging_charge = 0;
            @endphp
            @if ($order->order_type == 'parcel')
              <tr>
                <td class="col-item"><span class="inv-item-name">{{ translate('messages.delivery_charge') }}</span></td>
                <td class="col-qty">1</td>
                <td class="col-price">{{ \App\CentralLogics\Helpers::format_currency($order->delivery_charge) }}</td>
                <td class="col-disc">&mdash;</td>
                <td class="col-total">{{ \App\CentralLogics\Helpers::format_currency($order->delivery_charge) }}</td>
              </tr>
            @else
              @php
                if ($order->prescription_order == 1) {
                    $sub_total = $order['order_amount'] - $order['delivery_charge'] - $order['total_tax_amount'] - $order['dm_tips'] + $order['store_discount_amount'];
                }
              @endphp
              @php
                  $detailsCount = max($order->details->count(), 1);
                  $derivedItemSubtotal = max(
                      (float)$order['order_amount']
                      + (float)$order['store_discount_amount']
                      + (float)$order['flash_admin_discount_amount']
                      + (float)$order['flash_store_discount_amount']
                      + (float)$order['coupon_discount_amount']
                      + (float)$order['ref_bonus_amount']
                      - (float)$order['extra_packaging_amount']
                      - (float)$order['total_tax_amount']
                      - (float)$order['delivery_charge']
                      - (float)$order['additional_charge']
                      - (float)$order['dm_tips'],
                      0
                  );
              @endphp
              @foreach ($order->details as $detail)
                @php
                    $displayItemPayload = $detail->display_item_details ?? [];
                    $isEcommerceOrder = $order->store?->module?->module_type == 'ecommerce';
                    $detailItemId = (int) (
                        data_get($detail, 'item_id')
                        ?: data_get($displayItemPayload, 'item_id', data_get($displayItemPayload, 'id', 0))
                    );
                    $detailCampaignId = (int) (
                        data_get($detail, 'item_campaign_id')
                        ?: data_get($displayItemPayload, 'item_campaign_id', 0)
                    );
                    $currentCatalogItem = null;
                    if ($isEcommerceOrder) {
                        $currentCatalogItem = $detailItemId > 0
                            ? \App\Models\Item::withoutGlobalScopes()->find($detailItemId)
                            : ($detailCampaignId > 0 ? \App\Models\ItemCampaign::withoutGlobalScopes()->find($detailCampaignId) : null);
                    }
                    $detailQuantity     = max((int) ($detail->display_quantity ?? ($detail['quantity'] ?? 1)), 1);
                    $detailUnitPrice    = (float) ($detail->display_price ?? ($detail['price'] ?? 0));
                    if ($detailUnitPrice <= 0) {
                        $detailUnitPrice = (float) data_get($displayItemPayload, 'price', 0);
                    }
                    if ($detailUnitPrice <= 0 && $detailsCount === 1 && $derivedItemSubtotal > 0) {
                        $detailUnitPrice = round($derivedItemSubtotal / $detailQuantity, config('round_up_to_digit'));
                    }
                    $amount = round($detailUnitPrice * $detailQuantity, config('round_up_to_digit'));
                    if ($amount <= 0 && $detailsCount === 1 && $derivedItemSubtotal > 0) {
                        $amount = round($derivedItemSubtotal, config('round_up_to_digit'));
                    }
                    $itemName = $detail->display_item_name
                        ?? data_get($displayItemPayload, 'name',
                           data_get($displayItemPayload, 'title', translate('messages.Item deleted!')));
                    $foodVariations      = json_decode($detail['variation'] ?? '[]', true) ?: [];
                    $legacyFoodVarRow    = is_array($foodVariations[0] ?? null) ? $foodVariations[0] : [];
                    $displayableVariations = \App\CentralLogics\Helpers::getOrderVariationDisplayData(
                        $detail['variation'] ?? null, $displayItemPayload
                    );
                    $addOns   = json_decode($detail['add_ons'] ?? '[]', true) ?: [];
                    $item_dis = (float) ($detail['discount_on_item'] ?? 0);
                    $dis_by   = $detail['discount_on_product_by'] ?? '';
                    // Row-level discount (total for this row, not per unit)
                    $rowDiscount = $item_dis > 0
                        ? ($dis_by === 'store_discount' ? $item_dis : round($item_dis * $detailQuantity, config('round_up_to_digit')))
                        : 0;
                    if ($rowDiscount <= 0 && $isEcommerceOrder) {
                        $itemDiscountValue = (float) data_get($displayItemPayload, 'discount', data_get($currentCatalogItem, 'discount', data_get($detail->item, 'discount', 0)));
                        $itemDiscountType = data_get($displayItemPayload, 'discount_type', data_get($currentCatalogItem, 'discount_type', data_get($detail->item, 'discount_type')));

                        if ($itemDiscountValue > 0) {
                            $rowDiscount = $itemDiscountType === 'percent'
                                ? round(($detailUnitPrice * $itemDiscountValue / 100) * $detailQuantity, config('round_up_to_digit'))
                                : round($itemDiscountValue * $detailQuantity, config('round_up_to_digit'));
                        }
                    }

                    if ($isEcommerceOrder) {
                        $fallback_delivery_charge += (float) data_get($displayItemPayload, 'item_delivery_charge', data_get($currentCatalogItem, 'item_delivery_charge', data_get($detail->item, 'item_delivery_charge', 0))) * $detailQuantity;
                        $fallback_packaging_charge += (float) data_get($displayItemPayload, 'item_packaging_charge', data_get($currentCatalogItem, 'item_packaging_charge', data_get($detail->item, 'item_packaging_charge', 0))) * $detailQuantity;
                    }
                @endphp
                <tr>
                  <td class="col-item">
                    <div class="inv-item-name">{{ $loop->iteration }}. {{ $itemName }}</div>
                    {{-- Variations --}}
                    @if ($order->store && $order->store->module && $order->store->module->module_type == 'food')
                      @foreach ($foodVariations as $variation)
                        @if (isset($variation['name'], $variation['values']))
                          <div class="inv-item-meta">
                            <strong>{{ $variation['name'] }}:</strong>
                            @foreach (($variation['values'] ?? []) as $value)
                              {{ data_get($value,'label','') }}
                              @if (data_get($value,'optionPrice',0) > 0)
                                (+{{ \App\CentralLogics\Helpers::format_currency(data_get($value,'optionPrice',0)) }})
                              @endif
                            @endforeach
                          </div>
                        @else
                          @foreach ($legacyFoodVarRow as $k1 => $v1)
                            <div class="inv-item-meta">{{ $k1 }}: <strong>{{ $v1 }}</strong></div>
                          @endforeach
                          @break
                        @endif
                      @endforeach
                    @else
                      @foreach ($displayableVariations as $variation)
                        <div class="inv-item-meta">
                          {{ data_get($variation,'label','') }}: <strong>{{ \Illuminate\Support\Str::limit(data_get($variation,'value',''), 40, '...') }}</strong>
                        </div>
                      @endforeach
                    @endif
                    {{-- Add-ons --}}
                    @foreach ($addOns as $addon)
                      <div class="inv-item-addon">
                        + {{ data_get($addon,'name','') }}
                        × {{ data_get($addon,'quantity',0) }}
                        ({{ \App\CentralLogics\Helpers::format_currency(data_get($addon,'price',0)) }})
                      </div>
                      @php
                          $add_ons_cost += data_get($addon,'price',0) * data_get($addon,'quantity',0);
                      @endphp
                    @endforeach
                  </td>
                  <td class="col-qty">{{ $detailQuantity }}</td>
                  <td class="col-price">{{ \App\CentralLogics\Helpers::format_currency($detailUnitPrice) }}</td>
                  <td class="col-disc">
                    @if ($rowDiscount > 0)
                      - {{ \App\CentralLogics\Helpers::format_currency($rowDiscount) }}
                    @else
                      &mdash;
                    @endif
                  </td>
                  <td class="col-total">{{ \App\CentralLogics\Helpers::format_currency($amount) }}</td>
                </tr>
                @php
                    $sub_total          += $amount;
                    $total_tax          += (float) ($detail['tax_amount'] ?? 0) * $detailQuantity;
                    $total_item_discount += $rowDiscount;
                @endphp
              @endforeach
              @php
                  $sub_total = $sub_total > 0 ? $sub_total : $derivedItemSubtotal;
              @endphp
            @endif
          </tbody>
        </table>

        {{-- ── Summary ──────────────────────────────── --}}
        @php
            $del_c       = (float)($order['delivery_charge'] ?? 0);
            $tips        = (float)($order['dm_tips'] ?? 0);
            $tax_amount  = (float)($order['total_tax_amount'] ?? 0);
            $coupon_disc = (float)($order['coupon_discount_amount'] ?? 0);
            $ref_bonus   = (float)($order['ref_bonus_amount'] ?? 0);
            $extra_pkg   = (float)($order['extra_packaging_amount'] ?? 0);
            if ($extra_pkg <= 0 && $fallback_packaging_charge > 0) {
                $extra_pkg = round($fallback_packaging_charge, config('round_up_to_digit'));
            }
            $display_extra_pkg = $extra_pkg;
            $add_charge  = (float)($order['additional_charge'] ?? 0);

            // Discount = store_discount + flash discounts
            $order_store_discount     = (float)($order['store_discount_amount'] ?? 0)
                                      + (float)($order['flash_admin_discount_amount'] ?? 0)
                                      + (float)($order['flash_store_discount_amount'] ?? 0);
            $effective_store_discount = $total_item_discount > 0.009
                ? $total_item_discount
                : $order_store_discount;

            $summarySubtotal = (float)($sub_total + $add_ons_cost);
            $freeDeliveryEligibleAmount = max($summarySubtotal - $effective_store_discount - $coupon_disc - $ref_bonus, 0);
            $freeDeliverySettings = \App\Models\BusinessSetting::whereIn('key', [
                'free_delivery_over',
                'admin_free_delivery_status',
                'admin_free_delivery_option',
            ])->pluck('value', 'key');
            $adminFreeDeliveryStatus = (int) ($freeDeliverySettings['admin_free_delivery_status'] ?? 0);
            $adminFreeDeliveryOption = $freeDeliverySettings['admin_free_delivery_option'] ?? null;
            $freeDeliveryOver = (float) ($freeDeliverySettings['free_delivery_over'] ?? 0);
            $freeDeliveryApplied = filled($order['free_delivery_by'] ?? null)
                || (bool) ($order->store?->free_delivery ?? false)
                || (
                    $adminFreeDeliveryStatus === 1
                    && (
                        $adminFreeDeliveryOption === 'free_delivery_to_all_store'
                        || (
                            $adminFreeDeliveryOption === 'free_delivery_by_order_amount'
                            && $freeDeliveryOver > 0
                            && $freeDeliveryEligibleAmount >= $freeDeliveryOver
                        )
                    )
                );
            if ($freeDeliveryApplied) {
                $del_c = 0;
            } elseif ($del_c <= 0 && $fallback_delivery_charge > 0) {
                $del_c = round(
                    app(\App\Services\DeliveryChargeService::class)->applyMaximumLimit($fallback_delivery_charge),
                    config('round_up_to_digit')
                );
            }

            $storedOrderAmount = (float)$order->order_amount;
            $invoiceTotal = $storedOrderAmount;
            $financialSummary = $order->financialSummary();
        @endphp

        <div class="inv-summary">
          @if ($order->order_type != 'parcel')
            <div class="inv-summary-row">
              <span class="inv-summary-lbl">
                {{ translate('messages.subtotal') }}
                @if ($order->tax_status == 'included') ({{ translate('messages.TAX_Included') }}) @endif
              </span>
              <span class="inv-summary-val">{{ \App\CentralLogics\Helpers::format_currency($sub_total + $add_ons_cost) }}</span>
            </div>
            @if ($effective_store_discount > 0)
              <div class="inv-summary-row discount">
                <span class="inv-summary-lbl">{{ translate('messages.discount') }}</span>
                <span class="inv-summary-val">- {{ \App\CentralLogics\Helpers::format_currency($effective_store_discount) }}</span>
              </div>
            @endif
            @if ($coupon_disc > 0)
              <div class="inv-summary-row coupon">
                <span class="inv-summary-lbl">{{ translate('messages.coupon_discount') }}</span>
                <span class="inv-summary-val">- {{ \App\CentralLogics\Helpers::format_currency($coupon_disc) }}</span>
              </div>
            @endif
            @if ($ref_bonus > 0)
              <div class="inv-summary-row coupon">
                <span class="inv-summary-lbl">{{ translate('messages.Referral_Discount') }}</span>
                <span class="inv-summary-val">- {{ \App\CentralLogics\Helpers::format_currency($ref_bonus) }}</span>
              </div>
            @endif
            @if ($order->tax_status == 'excluded' && $tax_amount > 0 || $order->tax_status == null && $tax_amount > 0)
              <div class="inv-summary-row">
                <span class="inv-summary-lbl">{{ translate('messages.vat/tax') }}</span>
                <span class="inv-summary-val">+ {{ \App\CentralLogics\Helpers::format_currency($tax_amount) }}</span>
              </div>
            @endif
            @if ($del_c > 0)
              <div class="inv-summary-row">
                <span class="inv-summary-lbl">{{ translate('messages.delivery_charge') }}</span>
                <span class="inv-summary-val">{{ \App\CentralLogics\Helpers::format_currency($del_c) }}</span>
              </div>
            @endif
            @if ($tips > 0)
              <div class="inv-summary-row">
                <span class="inv-summary-lbl">{{ translate('messages.delivery_man_tips') }}</span>
                <span class="inv-summary-val">+ {{ \App\CentralLogics\Helpers::format_currency($tips) }}</span>
              </div>
            @endif
            @if ($add_charge > 0)
              <div class="inv-summary-row">
                <span class="inv-summary-lbl">{{ \App\CentralLogics\Helpers::get_business_data('additional_charge_name') ?? translate('messages.additional_charge') }}</span>
                <span class="inv-summary-val">+ {{ \App\CentralLogics\Helpers::format_currency($add_charge) }}</span>
              </div>
            @endif
            @if ($display_extra_pkg > 0)
              <div class="inv-summary-row">
                <span class="inv-summary-lbl">{{ translate('messages.Extra_Packaging_Amount') }}</span>
                <span class="inv-summary-val">+ {{ \App\CentralLogics\Helpers::format_currency($display_extra_pkg) }}</span>
              </div>
            @endif
          @endif

          <div class="inv-summary-row total">
            <span class="inv-summary-lbl">
              Invoice Total
              @if ($order->order_type == 'parcel' && $order->tax_status == 'included')
                ({{ translate('messages.TAX_Included') }})
              @endif
            </span>
            <span class="inv-summary-val">{{ \App\CentralLogics\Helpers::format_currency($invoiceTotal) }}</span>
          </div>

          <div style="border-top:1px solid #e2e8f0;margin-top:6px;padding-top:5px;">
            @if (abs($financialSummary['exchange_adjustment']) > 0.0005)
              <div class="inv-summary-row" style="font-size:11px;padding-top:3px;">
                <span>Exchange Adjustment</span>
                <span>{{ $financialSummary['exchange_adjustment'] > 0 ? '+' : '' }}{{ \App\CentralLogics\Helpers::format_currency($financialSummary['exchange_adjustment']) }}</span>
              </div>
            @endif
            <div class="inv-summary-row paid" style="font-size:11px;padding-top:3px;">
              <span>Advance Received</span>
              <span>{{ \App\CentralLogics\Helpers::format_currency($financialSummary['advance_received']) }}</span>
            </div>
            <div class="inv-summary-row paid" style="font-size:11px;padding-top:3px;">
              <span>Paid Amount</span>
              <span>{{ \App\CentralLogics\Helpers::format_currency($financialSummary['paid_amount']) }}</span>
            </div>
            <div class="inv-summary-row due" style="font-size:12px;padding-top:5px;margin-top:3px;">
              <span>Remaining Due</span>
              <span>{{ \App\CentralLogics\Helpers::format_currency($financialSummary['remaining_due']) }}</span>
            </div>
            <div class="inv-summary-row" style="font-size:11px;padding-top:3px;">
              <span>Courier COD Amount</span>
              <span>{{ \App\CentralLogics\Helpers::format_currency($financialSummary['courier_collectable']) }}</span>
            </div>
          </div>
        </div>

        {{-- ── Footer ───────────────────────────────── --}}
        <div class="inv-footer">
          <p class="inv-footer-ty">{{ translate('THANK YOU') }}</p>
          <p class="inv-footer-copy">
            &copy; {{ $businessName }}.
            @if ($footerText) {{ $footerText }} @endif
          </p>
          <p class="inv-footer-web">{{ parse_url((string) config('app.front_end_url'), PHP_URL_HOST) }}</p>
        </div>

      </div>{{-- .inv-card --}}
    </div>{{-- .inv-wrap --}}
  </div>{{-- #printableArea --}}
</div>
