@php
    $invConfig = $company->invoice_configuration ? json_decode($company->invoice_configuration, true) : [];
    $invConfig = is_array($invConfig) ? $invConfig : [];
    $isGst = ($company->tax_is_gst ?? 'No') === 'Yes';
    $collectTax = ($company->collect_tax ?? 'No') === 'Yes';
    $outletStateCode = $sale->outlet && $sale->outlet->state ? ($sale->outlet->state->state_code ?? null) : null;
    $customerStateCode = $sale->customer && $sale->customer->state ? ($sale->customer->state->state_code ?? null) : null;
    $isIntraState = ($customerStateCode === null) || ($outletStateCode === null) || ($customerStateCode === $outletStateCode);
    $vatObjects = $sale->sale_vat_objects ? json_decode($sale->sale_vat_objects, true) : [];
    $vatObjects = is_array($vatObjects) ? $vatObjects : [];
    $summaryTaxes = [];
    foreach ($vatObjects as $v) {
        $taxName = $v['tax_field_type'] ?? $v['tax_field_name'] ?? '';
        if (!$taxName) continue;
        $amt = (float) ($v['tax_field_amount'] ?? 0);
        $pct = (float) ($v['tax_field_percentage'] ?? 0);
        if (!isset($summaryTaxes[$taxName])) {
            $summaryTaxes[$taxName] = ['amount' => 0, 'rate' => $pct];
        }
        $summaryTaxes[$taxName]['amount'] += $amt;
        if ($pct > 0 && $summaryTaxes[$taxName]['rate'] == 0) {
            $summaryTaxes[$taxName]['rate'] = $pct;
        }
    }
    $defaultHsn = $invConfig['default_hsn_code'] ?? '0000';
    $totalItemDiscount = 0;
@endphp
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ __('Sale No') }}: {{ $sale->sale_no }}</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{{ asset('public/backend_assets/css/invoice-all.css') }}?v={{ @filemtime(public_path('backend_assets/css/invoice-all.css')) ?: time() }}" />
</head>
<body class="invoice-56mm invoice-80mm">
    <!-- HEADER -->
    <table class="header-table">
        <tr>
            <td class="company-info">
                @php $invoice_logo = $company->invoice_logo ?? null; @endphp
                @if($invoice_logo)
                    <img src="{{ asset('public/uploads/site_settings/' . $invoice_logo) }}" alt="Logo" class="logo">
                @endif
                <h2 class="heading-title">{{ $company->business_name ?? '' }}</h2>
                @if($sale->outlet)
                    <p>Outlet: {{ $sale->outlet->outlet_name ?? '' }}</p>
                    <p>Phone: {{ $sale->outlet->phone ?? '' }}</p>
                    <p>Email: {{ $sale->outlet->email ?? '' }}</p>
                    <p>Address: {{ $sale->outlet->address ?? '' }}</p>
                    @if($isGst && $collectTax)
                        @if($sale->outlet->state && ($sale->outlet->state->state_name || $sale->outlet->state->state_code))
                            <p>{{ __('Outlet State') }}: {{ $sale->outlet->state->state_name ?? '' }} ({{ $sale->outlet->state->state_code ?? '' }})</p>
                        @endif
                        @if($sale->outlet->gstin)
                            <p>{{ __('Outlet GSTIN') }}: {{ $sale->outlet->gstin }}</p>
                        @endif
                    @endif
                @endif
            </td>
        </tr>
    </table>

    <!-- CUSTOMER + SALE INFO -->
    <table class="customer-sale-info" style="margin-top:10px">
        <tr>
            <td width="50%" valign="top">
                <div class="heading-title">{{ __('Customer') }}</div>
                <table class="info-table">
                    @if($sale->customer)
                        @if($sale->customer->name)
                        <tr><td>{{ __('Name') }}</td><td>: {{ $sale->customer->name }}</td></tr>
                        @endif
                        @if($sale->customer->phone)
                        <tr><td>{{ __('Phone') }}</td><td>: {{ $sale->customer->phone }}</td></tr>
                        @endif
                        @if($sale->customer->email)
                        <tr><td>{{ __('Email') }}</td><td>: {{ $sale->customer->email }}</td></tr>
                        @endif
                        @if($sale->customer->address)
                        <tr><td>{{ __('Address') }}</td><td>: {{ $sale->customer->address }}</td></tr>
                        @endif
                        @if($isGst && $collectTax)
                            @if($sale->customer->gst_number)
                            <tr><td>{{ __('GSTIN') }}</td><td>: {{ $sale->customer->gst_number }}</td></tr>
                            @endif
                            @if($sale->customer->state && ($sale->customer->state->state_name || $sale->customer->state->state_code))
                            <tr><td>{{ __('Customer State') }}</td><td>: {{ $sale->customer->state->state_name ?? '' }} ({{ $sale->customer->state->state_code ?? '' }})</td></tr>
                            @endif
                        @endif
                    @else
                        <tr><td>{{ __('Name') }}</td><td>: {{ __('Walk-in Customer') }}</td></tr>
                    @endif
                </table>
            </td>
            <td width="50%" valign="top">
                <div class="heading-title">{{ __('Sale') }}</div>
                <table class="info-table">
                    @if($sale->sale_no)
                    <tr><td>{{ __('Sale No') }}</td><td>: {{ $sale->sale_no }}</td></tr>
                    @endif
                    @php
                        $dateTimeString = null;
                        if (!empty($sale->date_time)) {
                            $date = \Carbon\Carbon::parse($sale->date_time);
                            $dateTimeString = $date->format('Y/m/d g:ia');
                            $dateTimeString = strtoupper(substr($dateTimeString, 0, -2)) . ' ' . substr($dateTimeString, -2);
                        } elseif (!empty($sale->sale_date)) {
                            $date = \Carbon\Carbon::parse($sale->sale_date);
                            $dateTimeString = $date->format('Y/m/d');
                        }
                    @endphp
                    @if(!empty($dateTimeString))
                    <tr><td>{{ __('Date Time') }}</td><td>: {{ $dateTimeString }}</td></tr>
                    @endif
                    @if($sale->employee)
                    <tr><td>{{ __('Sales By') }}</td><td>: {{ $sale->employee->name }}</td></tr>
                    @endif
                    <tr><td>{{ __('Status') }}</td><td>: {{ $sale->due_amount > 0 ? __('Due') : __('Paid') }}</td></tr>
                </table>
            </td>
        </tr>
    </table>

    <!-- ITEMS TABLE -->
    <table class="items-table" style="margin-top:10px">
        <thead>
            <tr>
                <th width="5%" class="col-first">#</th>
                @if($isGst && isset($invConfig['show_hsn_code']) && $invConfig['show_hsn_code'] == 'Yes')
                <th width="6%">{{ __('HSN') }}</th>
                @endif
                <th width="{{ $isGst && isset($invConfig['show_hsn_code']) && $invConfig['show_hsn_code'] == 'Yes' ? '22%' : '25%' }}">{{ __('Item') }}</th>
                <th width="15%">{{ __('IMEI/Serial') }}</th>
                <th width="8%" class="col-amount">{{ __('Qty') }}</th>
                <th width="12%" class="col-amount">{{ __('Unit Price') }}</th>
                <th width="12%" class="col-last">{{ __('Total') }}</th>
            </tr>
        </thead>
        <tbody>
            @php $i = 0; @endphp
            @if($sale->saleDetails && $sale->saleDetails->count() > 0)
                @foreach($sale->saleDetails as $detail)
                    @php
                        $i++;
                        $lineSubtotal = $detail->qty * $detail->menu_price_with_discount;
                        $lineTotal = $lineSubtotal;
                        $detailTaxDisplay = '';
                        $itemTaxType = $detail->item && $detail->item->tax_type ? $detail->item->tax_type : 'Inclusive';
                        $menuTaxes = $detail->menu_taxes ? json_decode($detail->menu_taxes, true) : [];
                        $menuTaxes = is_array($menuTaxes) ? $menuTaxes : [];
                        foreach ($menuTaxes as $t) {
                            $name = $t['tax_field_name'] ?? $t['tax_field_type'] ?? '';
                            $amt = (float) ($t['tax_field_amount'] ?? 0);
                            $pct = (float) ($t['tax_field_percentage'] ?? 0);
                            if ($name && $amt > 0) {
                                $detailTaxDisplay .= ($detailTaxDisplay ? ', ' : '') . $name . ($pct > 0 ? ' ' . $pct . '%' : '') . ' - ' . formatAmount($amt);
                            }
                        }
                        if ($detailTaxDisplay && !$isIntraState) {
                            $detailTaxDisplay .= ' (' . __($itemTaxType) . ')';
                        }
                        $hsnCode = ($detail->item && $detail->item->hsn_code) ? $detail->item->hsn_code : ($defaultHsn ?? '0000');
                    @endphp
                    <tr>
                        <td class="col-first">{{ $i }}</td>
                        @if($isGst && isset($invConfig['show_hsn_code']) && $invConfig['show_hsn_code'] == 'Yes')
                        <td>{{ $hsnCode }}</td>
                        @endif
                        <td>
                            @if($detail->item)
                                @if($detail->item->parent_id && $detail->item->parent)
                                    {{ $detail->item->parent->name }} - {{ $detail->item->name }}
                                @else
                                    {{ $detail->item->name }}
                                @endif
                                @if($detail->item->code)
                                    ({{ $detail->item->code }})
                                @endif
                            @endif
                            @include('sale::sale.partials.invoice-item-warranty-guarantee', ['detail' => $detail])
                        </td>
                        <td>
                            @if($detail->expiry_imei_serial)
                                @if($detail->item && in_array($detail->item->type, ['IMEI_Product', 'Serial_Product']))
                                    {{ $detail->item->type === 'IMEI_Product' ? 'IMEI' : 'Serial' }}: {{ $detail->expiry_imei_serial }}
                                @elseif($detail->item && $detail->item->type === 'Medicine_Product')
                                    {{ $detail->expiry_imei_serial }}
                                @else
                                    {{ $detail->expiry_imei_serial }}
                                @endif
                            @else
                                -
                            @endif
                        </td>
                        <td class="col-amount">{{ $detail->qty }}</td>
                        <td class="col-amount">{{ formatAmount($detail->menu_unit_price) }}</td>
                        <td class="col-last">{{ formatAmount($lineTotal) }}</td>
                    </tr>
                @endforeach
            @endif
        </tbody>
    </table>

    <!-- SUMMARY -->
    <table style="margin-top:10px">
        <tr>
            <td valign="top">
                <table class="summary-table">
                    <tr>
                        <td>{{ __('Subtotal') }}</td>
                        <td>{{ formatAmount($sale->sub_total) }}</td>
                    </tr>
                    @if(isset($sale->total_item_discount_amount) && $sale->total_item_discount_amount > 0)
                    <tr>
                        <td>{{ __('Item Discount') }}</td>
                        <td>{{ formatAmount($sale->total_item_discount_amount) }}</td>
                    </tr>
                    @endif
                    @if(isset($sale->sub_total_discount_amount) && $sale->sub_total_discount_amount > 0)
                    <tr>
                        <td>{{ __('Order Discount') }}</td>
                        <td>{{ formatAmount($sale->sub_total_discount_amount) }}</td>
                    </tr>
                    @endif
                    @if($sale->total_discount_amount > 0 && !isset($sale->total_item_discount_amount) && !isset($sale->sub_total_discount_amount))
                    <tr>
                        <td>{{ __('Discount') }}</td>
                        <td>{{ formatAmount($sale->total_discount_amount) }}</td>
                    </tr>
                    @endif
                    @foreach($summaryTaxes ?? [] as $taxName => $taxData)
                        @if(($taxData['amount'] ?? 0) > 0)
                    <tr>
                        <td>{{ $taxName }}{{ ($taxData['rate'] ?? 0) > 0 ? ' (' . $taxData['rate'] . '%)' : '' }}</td>
                        <td>{{ formatAmount($taxData['amount']) }}</td>
                    </tr>
                        @endif
                    @endforeach
                    @if($sale->delivery_charge > 0)
                    <tr>
                        <td>{{ __('Delivery Charge') }}</td>
                        <td>{{ formatAmount($sale->delivery_charge) }}</td>
                    </tr>
                    @endif
                    <tr class="grand-total">
                        <td>{{ __('Grand Total') }}</td>
                        <td>{{ formatAmount($sale->total_payable ?? $sale->grand_total) }}</td>
                    </tr>
                    <tr>
                        <td>{{ __('Previous Due Amount') }}</td>
                        <td>{{ formatAmount($sale->previous_due ?? 0) }}</td>
                    </tr>
                    <tr>
                        <td>{{ __('Paid Amount') }}</td>
                        <td>{{ formatAmount($sale->paid_amount) }}</td>
                    </tr>
                    <tr>
                        <td>{{ __('Due Amount') }}</td>
                        <td>{{ formatAmount($sale->due_amount) }}</td>
                    </tr>
                    @if(isset($invConfig['show_payment_method']) && $invConfig['show_payment_method'] == 'Yes' && $sale->salePayments && $sale->salePayments->count() > 0)
                    <tr>
                        <td>{{ $invConfig['payment_method_label'] ?? __('Payment Method') }}</td>
                        <td></td>
                    </tr>
                    @foreach($sale->salePayments as $payment)
                    <tr>
                        <td>{{ $payment->paymentMethod->name ?? __('Cash') }}</td>
                        <td>{{ formatAmount($payment->amount) }}</td>
                    </tr>
                    @endforeach
                    @endif
                </table>
            </td>
        </tr>
    </table>

    <!-- FOOTER -->
    @if(!empty($company->term_conditions))
    <div class="footer">
        {!! $company->term_conditions !!}
    </div>
    @endif

    @if(!empty($company->invoice_footer))
    <div class="footer">
        {!! $company->invoice_footer !!}
    </div>
    @endif

    @include('sale::sale.partials.invoice-qr', [
        'sale' => $sale,
        'invConfig' => $invConfig,
        'businessName' => $company->business_name ?? '',
    ])
</body>
</html>
